import { merge } from 'xe-utils';
import dayjs from 'dayjs';
import {
  getPMode,
  enterpriseGuid,
  getIsReadonlyByActiveKey,
  fileUploadElement,
  enterpriseFormField,
  debtcodeFormField,
  conststagBtn,
} from './baseField';
import { message } from 'ant-design-vue';
import borrChange from '@/views/ycys/debtInterSys/borrChange/index.vue';

const floatModeOptions = [
  { value: '3', label: '加点' },
  { value: '4', label: '减点' },
];

/****** 举借债务数据 开始 *****************/
const zwjjTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'GUID',
    title: 'ID',
    align: 'center',
    fixed: 'left',
    ui: { self: { minWidth: 80 } },
  },
  {
    parent: 0,
    field: 'ENTERPRISE',
    title: '债务单位',
    align: 'left',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'NAME',
    title: '债务名称',
    align: 'left',
    fixed: 'left',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'DEBTTYPENAME',
    title: '债务类别',
    align: 'center',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'BOOKDATE',
    title: '签订日期',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'AGREENO',
    title: '协议号',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'LOANTYPENAME',
    title: '债权类型',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'LOANERNAME',
    title: '债权人',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'LOANERFULLNAME',
    title: '债权人全称',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'ITEMNAME',
    title: '项目名称',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'PAYOUTNAME',
    title: '协议(合同)名称',
    ui: { self: { minWidth: 180 } },
  },
  {
    parent: 0,
    field: 'AGREERMBMONEY',
    title: '协议金额(万元)',
    fixed: 'right',
    ui: {
      self: {
        minWidth: 130,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RESTMONEY',
    title: '债务余额(原币)',
    fixed: 'right',
    ui: {
      self: {
        minWidth: 130,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'OVERDUEMONEY',
    title: '逾期金额(原币)',
    ui: {
      self: { minWidth: 120 },
      formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
          /(?:\.0*|(\.\d+?)0+)$/,
          '$1',
        );
      },
    },
  },
  {
    parent: 0,
    field: 'RATETYPENAME',
    title: '利率类型',
    ui: { self: { minWidth: 100 } },
  },
];
const zwjjSearchFields: Recordable[] = [
  enterpriseGuid,
  {
    field: 'DEBTNAME',
    title: '债务名称',
    component: 'Input',
    ui: {},
  },
  {
    field: 'LOANCODE',
    title: '债权人',
    component: 'ApiTreeSelect',
    ui: {
      props: {
        api: async (...args) => {
          const [{ dc, xe }] = args.slice(-1);
          const { http } = dc;
          const { mapTree, toArrayTree } = xe;
          const nodes: any[] = mapTree(
            toArrayTree(
              await http.form({
                url: '/lpzw/czItem/listItemCombo',
                data: { type: 3, BMTYPE: 28 },
              }),
              { parentKey: 'pid' },
            ),
            (item) => ({ ...item, disabled: item.children && item.children.length > 0 }),
          );
          return nodes;
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
    },
  },
  // {
  //   field: 'EXAMSTATE',
  //   title: '状态',
  //   component: 'ApiSelect',
  //   ui: {
  //     props: {
  //       api: async (...args) => {
  //         const lib = args.slice(-1)[0];
  //         const { http } = lib.dc;
  //         const data = { type: 4, BMTYPE: 17 };
  //         return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
  //       },
  //       labelField: 'text',
  //       valueField: 'id',
  //       immediate: true,
  //     },
  //   },
  // },
  // {
  //   field: 'BSB',
  //   title: '是否上报',
  //   component: 'Select',
  //   ui: {
  //     props: {
  //       options: [
  //         { value: '0', label: '否' },
  //         { value: '1', label: '是' },
  //       ],
  //     },
  //   },
  // },
  // {
  //   field: 'YEAR',
  //   title: '立项年度',
  //   component: 'DatePicker',
  //   required: true,
  //   ui: {
  //     custom: {
  //       default: (_, { dc: { store }, dayjs }) => dayjs(store.get('user', 'date')).format('YYYY'),
  //     },
  //     props: { picker: 'year', valueFormat: 'YYYY' },
  //   },
  // },
  {
    field: '[BEGINDATE, ENDDATE]',
    title: '签订日期',
    component: 'RangePicker',
    ui: {
      props: {
        placeholder: ['开始日期', '结束日期'],
        valueFormat: 'YYYY-MM-DD',
      },
    },
  },
  {
    field: 'DEBTTYPE',
    title: '债务类别',
    component: 'ApiTreeSelect',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const { toArrayTree } = lib.xe;
          return toArrayTree(
            await http.form({
              url: '/lpzw/czItem/listItemCombo',
              data: { type: 3, BMTYPE: 18 },
            }),
            { parentKey: 'pid' },
          );
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
    },
  },
  {
    field: 'LOANTYPE',
    title: '债权类型',
    component: 'ApiTreeSelect',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const { toArrayTree } = lib.xe;
          const data = { type: 3, BMTYPE: 19 };
          const ret = await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          return toArrayTree(ret, { parentKey: 'pid' });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
    },
  },
  {
    field: 'restMoneyNullFlag',
    title: '余额不为零',
    component: 'Checkbox',
    defaultValue: true,
    ui: {
      self: { colProps: { span: 2 } },
    },
  },
];

const zwjjTableButtons: Recordable[] = [
  {
    name: 'add',
    label: '新增',
    ui: {
      props: {
        type: 'primary',
        preIcon: 'bi:plus-lg',
        ifShow: function (_, { transfer }) {
          const { tabType, bgAdmin } = transfer;
          return (!tabType || tabType === 'pZwjjBase') && !bgAdmin;
        },
      },
      events: {
        onClick: async (_, _01, { memory }, { dc: { open, http, Confirm }, xe: { get } }) => {
          const subs = { eGridZwjjBack: 4, eGridZwjjRate: 5 };
          let transfer = {
            eFormZwjjBase: get(memory, 'pass.eFormZwjj.enterprise', {}),
            eGridZwjjBack: [],
            eGridZwjjInfo: [],
          };
          const stag = await http.post({
            url: '/lpzw/draft/getDraft',
            data: {
              menuId: 'pZwjjM',
            },
          });
          if (stag) {
            await new Promise((resolve) => {
              Confirm({
                iconType: 'info',
                title: '您有一条暂存记录,是否使用?',
                cancelText: () => '不使用',
                okText: () => '使用',
                onCancel: async () => {
                  resolve(false);
                },
                onOk: async () => {
                  transfer = JSON.parse(stag.info);
                  resolve(true);
                },
              });
            });
          }
          const layout = { id: 'pZwjjM' };
          const modal = {
            title: '新增举借项目',
            width: '75vw',
            // height: document.body.clientHeight * 0.75,
            minHeight: document.body.clientHeight * 0.75,
            defaultFullscreen: false,
            destroyOnClose: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
            centered: true,
            maskClosable: false,
          };
          const inner = {
            onOk: async (_, { origin }, { xe, dc: { close, http, validate } }) => {
              const ret = await validate();
              console.log('validate: ', ret);
              for (const isValidate of Object.values(ret)) if (isValidate !== true) return;
              const { get, isEmpty, omit, set } = xe;
              const GUID = await http.get({ url: '/lpzw/czDebt/getBaseGuid', data: {} });
              const baseInfo = get(origin, 'eFormZwjjBase');
              set(baseInfo, 'GUID', GUID as Number);
              const added: Recordable[] = [];
              const baseList = get(origin, 'eGridZwjjInfo', []);
              for (const base of baseList) {
                const parent = base.GUID ?? base._id;
                delete base._id;
                delete base.id;
                if (isEmpty(base)) continue;
                base.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                base.DEBTGUID = GUID;
                base.state = 'added';
                for (const key of Object.keys(subs)) {
                  const childrens = get(origin, key, []).filter(({ AMOUNT }) => AMOUNT == parent);
                  for (const child of childrens) {
                    child.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                    child.AMOUNT = base.GUID;
                    child.DEBTGUID = GUID;
                    child.CTYPE = subs[key];
                    child.state = 'added';
                    delete child._id;
                    delete child.id;
                    added.push(child);
                  }
                }
              }
              const subList: Recordable[] = [...baseList, ...added];
              const others = {
                eGridZwjjDiya: 1, // 抵押
                eGridZwjjZhiya: 14, // 质押
                eGridZwjjDanbao: 2, // 担保
                eGridZwjjCapital: 6, // 偿还本金
                eGridZwjjInterest: 7, // 罚息
              };
              const fileSubs = {
                GridZwjjFileBase: 0,
                GridZwjjFileCapital: 6,
                GridZwjjFileInterest: 7,
              };
              for (const key of Object.keys(others)) {
                for (const it of get(origin, key, [])) {
                  const val = omit(it, ['id']);
                  if (isEmpty(val)) continue;
                  val.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                  val.CTYPE = others[key];
                  val.DEBTGUID = GUID;
                  val.state = 'added';
                  subList.push(val);
                }
              }
              const fileList: Recordable[] = [];
              for (const key of Object.keys(fileSubs)) {
                const now = get(origin, key, []);
                if (!now.length) continue;
                const added: Recordable[] = [];
                for (const it of now) {
                  if (isEmpty(it)) continue;
                  it.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid', data: {} });
                  it.DEBTGUID = GUID;
                  it.CTYPE = fileSubs[key];
                  it.state = 'added';
                  added.push(it);
                }
                fileList.push(...added);
              }
              await http.post({
                url: '/lpzw/czDebt/saveDebt',
                data: {
                  baseInfo: omit(baseInfo, ['FINANCE_NATIONAL']),
                  option: 'added',
                  subList,
                  fileList,
                },
              });
              if (stag) {
                await http.post({
                  url: '/lpzw/draft/clearDraft',
                  data: {
                    menuId: 'pZwjjM',
                  },
                });
              }
              close(true);
            },
          };
          open({
            inner,
            layout,
            modal,
            transfer: {
              ...transfer,
              btnType: 'add',
            },
          });
        },
      },
    },
  },
  {
    name: 'view',
    label: '查看',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:eye',
        onClick: async (
          _,
          { $grid, row },
          { transfer: { tabType, bgAdmin } },
          { dayjs, dc: { open, http, store }, h },
        ) => {
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const subs = { eGridZwjjBack: 4, eGridZwjjRate: 5 };
          const eFormZwjjBase = await http.form({
            url: '/lpzw/czDebt/findDebtByGuid',
            data: { GUID: row.GUID, YEAR: year },
          });
          const { items: eGridZwjjInfo } = await http.form({
            url: '/lpzw/czDebt/listDebtSub',
            data: { DEBTGUID: row.GUID, YEAR: year, CTYPE: 3 },
          });
          const transfer = {
            GUID: row.GUID,
            isReadonly: true,
            eFormZwjjBase,
            eGridZwjjInfo,
            activeKey: '',
          };
          const getSubUrl = '/lpzw/czDebt/listDebtSub';
          const getSubArg = { DEBTGUID: row.GUID, YEAR: year };
          for (const key of Object.keys(subs)) {
            const { items } = await http.form({
              url: getSubUrl,
              data: { ...getSubArg, CTYPE: subs[key] },
            });
            transfer[key] = items;
          }
          if (tabType) {
            transfer.activeKey = tabType;
          }
          const layout = { id: 'pZwjjM' };
          const modal = {
            width: '75vw',
            minHeight: document.body.clientHeight * 0.75,
            defaultFullscreen: false,
            destroyOnClose: true,
            centered: true,
            open: true,
            showOkBtn: false,
            showCancelBtn: false,
          };

          const fields = {
            zwjjBaseFields,
            zwjjInfoTableFields,
            zwjjBackTableFields,
            zwjjRateTableFields,
            zwjjCapitalTableFields,
            zwjjInterestTableFields,
          };
          const slots = bgAdmin
            ? {
                title: () => [h(borrChange, { tabType, checkRow: row, fields })],
              }
            : {
                title: () => ['债务详情（', h('span', { style: 'color: red' }, '单位：万元'), '）'],
              };
          const inner = {};
          console.log('inner click: ', $grid, row, { inner, layout, modal, transfer });
          open({ inner, layout, modal, slots, transfer });
        },
      },
    },
  },
  {
    name: 'edit',
    label: '修改',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:pencil-square',
        onClick: async (
          _,
          { row },
          { transfer: { tabType } },
          { dayjs, dc: { open, http, store } },
        ) => {
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const subs = { eGridZwjjBack: 4, eGridZwjjRate: 5 };
          const eFormZwjjBase = await http.form({
            url: '/lpzw/czDebt/findDebtByGuid',
            data: { GUID: row.GUID, YEAR: year },
          });
          const { items: eGridZwjjInfo } = await http.form({
            url: '/lpzw/czDebt/listDebtSub',
            data: { DEBTGUID: row.GUID, YEAR: year, CTYPE: 3 },
          });
          const transfer = {
            GUID: row.GUID,
            eFormZwjjBase,
            eGridZwjjInfo,
            activeKey: '',
            checkRow: row,
            btnType: 'edit',
            isReadonly: row.ISLOCKED === 1,
            maxReportMonth: '',
          };
          if (row.ISLOCKED === 1) {
            const data = await http.form({
              url: '/lpzw/report/getMaxReportMonth',
              data: { ENTERPRISE_GUID: row.ENTERPRISEGUID },
            });
            transfer.maxReportMonth = data.month;
          }
          const getSubUrl = '/lpzw/czDebt/listDebtSub';
          const getSubArg = { DEBTGUID: row.GUID, YEAR: year };
          for (const key of Object.keys(subs)) {
            const { items } = await http.form({
              url: getSubUrl,
              data: { ...getSubArg, CTYPE: subs[key] },
            });
            transfer[key] = items;
          }
          if (tabType) {
            transfer.activeKey = tabType;
          }
          const layout = { id: 'pZwjjM' };
          const modal = {
            title: '编辑举借项目',
            width: '75vw',
            minHeight: document.body.clientHeight * 0.75,
            defaultFullscreen: false,
            destroyOnClose: true,
            centered: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
            maskClosable: false,
          };
          const inner = {
            onOk: async (_, { origin, memory }, { dc: { close }, xe }) => {
              const { get, isEmpty, isEqual, omit, set } = xe;
              const baseInfo = get(origin, 'eFormZwjjBase');
              const GUID = row.GUID;
              set(baseInfo, 'GUID', GUID);
              const removed: Recordable[] = [];
              const changed: Recordable[] = [];
              const added: Recordable[] = [];
              const baseList = get(origin, 'eGridZwjjInfo', []);
              removed.push(
                ...eGridZwjjInfo
                  .filter(({ GUID }) => GUID && baseList.findIndex((it) => it.GUID == GUID) < 0)
                  .map((it) => ({ GUID: it.GUID, state: 'removed' })),
              );
              for (const key of Object.keys(subs)) {
                const child = get(origin, key, []);
                removed.push(
                  ...transfer[key]
                    .filter(({ GUID }) => GUID && child.findIndex((it) => it.GUID == GUID) < 0)
                    .map((it) => ({ GUID: it.GUID, state: 'removed' })),
                );
              }

              for (const base of baseList) {
                const parent = base.GUID ?? base._id;
                delete base._id;
                delete base.id;
                if (isEmpty(base)) continue;
                if (!base.GUID) {
                  base.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                  base.DEBTGUID = GUID;
                  base.CTYPE = 3;
                  base.state = 'added';
                  added.push(base);
                } else {
                  const old = eGridZwjjInfo.find(({ GUID }) => base.GUID == GUID);
                  if (!isEqual(old, base)) {
                    base.state = 'modified';
                    changed.push(base);
                  }
                }
                for (const key of Object.keys(subs)) {
                  const childrens = get(origin, key, []).filter(({ AMOUNT }) => AMOUNT == parent);
                  for (const child of childrens) {
                    delete child._id;
                    delete child.id;
                    if (isEmpty(child)) continue;
                    if (!child.GUID) {
                      child.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid', data: {} });
                      child.AMOUNT = base.GUID;
                      child.DEBTGUID = GUID;
                      child.CTYPE = subs[key];
                      child.state = 'added';
                      added.push(child);
                    } else {
                      const old = transfer[key].find(({ GUID }) => child.GUID == GUID);
                      if (isEqual(old, child)) continue;
                      child.state = 'modified';
                      changed.push(child);
                    }
                  }
                }
              }
              const subList = [...removed, ...added, ...changed];
              const others = {
                eGridZwjjDiya: 1, // 抵押
                eGridZwjjZhiya: 14, // 质押
                eGridZwjjDanbao: 2, // 担保
                eGridZwjjCapital: 6, // 偿还本金
                eGridZwjjInterest: 7, // 罚息
              };
              const fileSubs = {
                GridZwjjFileBase: 0,
                GridZwjjFileCapital: 6,
                GridZwjjFileInterest: 7,
              };
              for (const key of Object.keys(others)) {
                const list = get(origin, key, []);
                const bak = get(memory, key, []);
                const removed = bak
                  .filter(({ GUID }) => list.findIndex((it) => it.GUID == GUID) < 0)
                  .map((it) => ({ GUID: it.GUID, state: 'removed' }));
                const changed: Recordable[] = [];
                const added: Recordable[] = [];
                for (const now of list) {
                  const val = omit(now, ['id']);
                  if (isEmpty(val)) continue;
                  const extra = { CTYPE: others[key], DEBTGUID: GUID };
                  if (!val.GUID) {
                    const cid = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                    added.push({ ...val, ...extra, state: 'added', GUID: cid });
                    continue;
                  }
                  const old = bak.find(({ GUID }) => val.GUID == GUID);
                  if (isEqual(val, old)) continue;
                  changed.push({ ...val, ...extra, state: 'modified', GUID: val.GUID });
                }

                subList.push(...removed, ...added, ...changed);
              }
              const fileList: Recordable[] = [];
              for (const key of Object.keys(fileSubs)) {
                const now = get(origin, key, []);
                const old = get(memory, key, []);
                if (!now.length && !old.length) continue;
                const added: Recordable[] = [];
                const changed: Recordable[] = [];
                const removed = old
                  .filter(({ GUID }) => GUID && now.findIndex((it) => it.GUID == GUID) < 0)
                  .map((it) => ({ GUID: it.GUID, state: 'removed' }));
                for (const it of now) {
                  const val = omit(it, ['id']);
                  if (isEmpty(val)) continue;
                  if (val.GUID) {
                    const bak = old.find(({ GUID }) => val.GUID == GUID);
                    if (isEqual(bak, val)) continue;
                    changed.push({ ...val, state: 'modified' });
                    continue;
                  }
                  val.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid', data: {} });
                  val.DEBTGUID = GUID;
                  val.CTYPE = fileSubs[key];
                  val.state = 'added';
                  added.push(val);
                }
                fileList.push(...removed, ...changed, ...added);
              }
              await http.post({
                url: '/lpzw/czDebt/saveDebt',
                data: {
                  baseInfo: omit(baseInfo, ['FINANCE_NATIONAL']),
                  option: 'modified',
                  subList,
                  fileList,
                },
              });
              close(true);
            },
          };
          open({ inner, layout, modal, transfer });
        },
        ifShow: function (_, { row: { ISLOCKED } }, { transfer }) {
          const { tabType } = transfer;
          return (ISLOCKED !== 1 || tabType) && !transfer.bgAdmin;
        },
      },
    },
  },
  {
    name: 'del',
    label: '删除',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:trash3',
        popConfirm: {
          title: '是否确认删除',
          confirm: async (_0, { row }, _2, { dc: { http, reload } }) => {
            await http.form({ url: '/lpzw/czDebt/deleteDebt', data: { GUIDS: row.GUID } });
            reload();
          },
        },
        ifShow: function (_, { row: { ISLOCKED } }, { transfer }) {
          return ISLOCKED !== 1 && !transfer.bgAdmin;
        },
      },
    },
  },
  {
    name: 'unLock',
    label: '解锁',
    tag: 'row',
    ui: {
      props: {
        icon: 'uil:unlock-alt',
        popConfirm: {
          title: '是否解锁数据',
          confirm: async (_0, { row }, _2, { dc: { http, reload } }) => {
            await http.form({ url: '/lpzw/czDebt/unLockDebtBase ', data: { GUID: row.GUID } });
            reload();
          },
        },
        ifShow: function (_, { row: { ISLOCKED } }, { transfer }, { dc: { store } }) {
          return ISLOCKED === 1 && store.get('user', 'isAdmin') && !transfer.bgAdmin;
        },
      },
    },
  },
  {
    name: 'agreeChange',
    label: '同意',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:check2',
        popConfirm: {
          title: '是否同意变更',
          confirm: async (_0, { row }, { transfer: { tabType } }, { dc: { http, reload } }) => {
            const data = await http.post({
              url: '/lpzw/debtChange/listChange',
              data: {
                type: tabType,
                debtBaseGuid: row.GUID,
                status: 1,
              },
            });
            if (!data.length) return message.error('暂无变更数据');
            let params;
            if (tabType === 'pZwjjBase') {
              const changeInfo = JSON.parse(data[0].changeInfo).newChangeForm;
              params = {
                option: 'modified',
                baseInfo: {
                  ...changeInfo,
                  GUID: row.GUID,
                },
              };
            } else {
              const changeInfo = JSON.parse(data[0].changeInfo);
              params = {
                option: 'modified',
                baseInfo: {
                  GUID: row.GUID,
                },
                subList: changeInfo.subList,
              };
            }
            await http.post({
              url: '/lpzw/czDebt/saveDebt',
              data: params,
            });
            await http.post({
              url: '/lpzw/debtChange/changeStatus ',
              data: {
                guid: row.CHANGE_GUID,
                status: 2,
              },
            });
            reload();
          },
        },
        ifShow: function (_, { row: { CHANGE_GUID } }, { transfer }) {
          return transfer.bgAdmin && CHANGE_GUID;
        },
      },
    },
  },
  {
    name: 'rejectChange',
    label: '拒绝',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:box-arrow-in-left',
        popConfirm: {
          title: '是否拒绝变更',
          confirm: async (_0, { row }, _2, { dc: { http, reload } }) => {
            await http.post({
              url: '/lpzw/debtChange/changeStatus ',
              data: {
                guid: row.CHANGE_GUID,
                status: 3,
              },
            });
            message.success('已拒绝变更');
            reload();
          },
        },
        ifShow: function (_, { row: { CHANGE_GUID } }, { transfer }) {
          return transfer.bgAdmin && CHANGE_GUID;
        },
      },
    },
  },
  {
    name: 'change',
    label: '变更',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:pencil-square',
        onClick: async (
          _,
          { row },
          { transfer: { tabType } },
          { dayjs, dc: { open, http, store }, h },
        ) => {
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const subs = { eGridZwjjBack: 4, eGridZwjjRate: 5 };
          const eFormZwjjBase = await http.form({
            url: '/lpzw/czDebt/findDebtByGuid',
            data: { GUID: row.GUID, YEAR: year },
          });
          const { items: eGridZwjjInfo } = await http.form({
            url: '/lpzw/czDebt/listDebtSub',
            data: { DEBTGUID: row.GUID, YEAR: year, CTYPE: 3 },
          });
          const transfer = {
            GUID: row.GUID,
            eFormZwjjBase,
            eGridZwjjInfo,
            activeKey: '',
            checkRow: row,
            btnType: 'edit',
            isReadonly: false,
            maxReportMonth: '',
          };
          // if (row.ISLOCKED === 1) {
          //   const data = await http.form({
          //     url: '/lpzw/report/getMaxReportMonth',
          //     data: { ENTERPRISE_GUID: row.ENTERPRISEGUID },
          //   });
          //   transfer.maxReportMonth = data.month;
          // }
          const getSubUrl = '/lpzw/czDebt/listDebtSub';
          const getSubArg = { DEBTGUID: row.GUID, YEAR: year };
          for (const key of Object.keys(subs)) {
            const { items } = await http.form({
              url: getSubUrl,
              data: { ...getSubArg, CTYPE: subs[key] },
            });
            transfer[key] = items;
          }
          if (tabType) {
            transfer.activeKey = tabType;
          }
          const layout = { id: 'pZwjjM' };
          const modal = {
            title: '变更举借项目',
            width: '75vw',
            minHeight: document.body.clientHeight * 0.75,
            defaultFullscreen: false,
            destroyOnClose: true,
            centered: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
            maskClosable: false,
          };
          const inner = {
            onOk: async (_, { origin, memory }, { dc: { close }, xe, dayjs }) => {
              const { get, isEmpty, isEqual, omit, set } = xe;
              const baseInfo: Object = get(origin, 'eFormZwjjBase', {});
              const GUID = row.GUID;
              set(baseInfo, 'GUID', GUID);
              let changeInfo = '';
              if (tabType === 'pZwjjBase') {
                const oldChangeForm = {};
                const newChangeForm = {};
                const fields = zwjjBaseFields.map((i) => i.field);
                const oldForm = memory.eFormZwjjBase;
                if (typeof oldForm.PLEDGE_DATE === 'number') {
                  oldForm.PLEDGE_DATE = dayjs(oldForm.PLEDGE_DATE).format('YYYY-MM-DD');
                }
                //排除的字段
                const removeFields = ['CREDITMONEY1', 'BMONEY'];
                Object.keys(baseInfo).forEach((key) => {
                  const newValue = baseInfo[key];
                  const oldValue = oldForm[key];
                  //对象暂不比较
                  if (
                    typeof newValue === 'object' ||
                    (!newValue && !oldValue && newValue !== 0 && oldValue !== 0) ||
                    removeFields.includes(key)
                  )
                    return;
                  if (newValue != oldValue && fields.includes(key)) {
                    newChangeForm[key] = newValue;
                    oldChangeForm[key] = oldValue;
                  }
                });
                //数据清空
                Object.keys(oldForm).forEach((key) => {
                  if (!Object.hasOwnProperty.call(baseInfo, key) && fields.includes(key)) {
                    newChangeForm[key] = '';
                    oldChangeForm[key] = oldForm[key];
                  }
                });
                if (
                  JSON.stringify(newChangeForm) !== '{}' ||
                  JSON.stringify(oldChangeForm) !== '{}'
                ) {
                  const info = {
                    newChangeForm,
                    oldChangeForm,
                    userName: store.get('user', 'userInfo').nickName,
                    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  };
                  changeInfo = JSON.stringify(info);
                }
              } else if (tabType === 'pZwjjInfo') {
                const fields = [
                  ...zwjjInfoTableFields,
                  ...zwjjBackTableFields,
                  ...zwjjRateTableFields,
                ].map((i) => i.field);
                //比较eGridZwjjInfo   eGridZwjjBack  eGridZwjjRate
                const removed: Recordable[] = [];
                const changed: Recordable[] = [];
                const added: Recordable[] = [];
                const oldList: Recordable[] = [];

                //排除的字段
                const removeFields = ['AMOUNTTEXT'];

                const baseList = get(origin, 'eGridZwjjInfo', []);
                removed.push(
                  ...eGridZwjjInfo
                    .filter(({ GUID }) => GUID && baseList.findIndex((it) => it.GUID == GUID) < 0)
                    .map((it) => ({ GUID: it.GUID, state: 'removed' })),
                );
                for (const key of Object.keys(subs)) {
                  const child = get(origin, key, []);
                  removed.push(
                    ...transfer[key]
                      .filter(({ GUID }) => GUID && child.findIndex((it) => it.GUID == GUID) < 0)
                      .map((it) => ({ GUID: it.GUID, state: 'removed' })),
                  );
                }
                for (const base of baseList) {
                  const parent = base.GUID ?? base._id;
                  delete base._id;
                  delete base.id;
                  if (isEmpty(base)) continue;
                  if (!base.GUID) {
                    base.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                    base.DEBTGUID = GUID;
                    base.CTYPE = 3;
                    base.state = 'added';
                    added.push(base);
                  } else {
                    const oldChangeForm = {};
                    const newChangeForm = {};
                    const old = eGridZwjjInfo.find(({ GUID }) => base.GUID == GUID);
                    if (!isEqual(old, base)) {
                      //获取修改了什么
                      Object.keys(base).forEach((key) => {
                        const newValue = base[key];
                        const oldValue = old[key];
                        if (
                          (!newValue && !oldValue && newValue !== 0 && oldValue !== 0) ||
                          removeFields.includes(key)
                        )
                          return;
                        if (newValue != oldValue && fields.includes(key)) {
                          newChangeForm[key] = newValue;
                          oldChangeForm[key] = oldValue;
                        }
                      });
                      if (
                        JSON.stringify(newChangeForm) !== '{}' ||
                        JSON.stringify(oldChangeForm) !== '{}'
                      ) {
                        changed.push({
                          ...newChangeForm,
                          state: 'modified',
                          GUID: base.GUID,
                        });
                        oldList.push(old);
                      }
                    }
                  }
                  for (const key of Object.keys(subs)) {
                    const childrens = get(origin, key, []).filter(({ AMOUNT }) => AMOUNT == parent);
                    for (const child of childrens) {
                      delete child._id;
                      delete child.id;
                      if (isEmpty(child)) continue;
                      if (!child.GUID) {
                        child.GUID = await http.get({ url: '/lpzw/czDebt/getSubGuid', data: {} });
                        child.AMOUNT = base.GUID;
                        child.DEBTGUID = GUID;
                        child.CTYPE = subs[key];
                        child.state = 'added';
                        added.push(child);
                      } else {
                        const oldChangeForm = {};
                        const newChangeForm = {};
                        const old = transfer[key].find(({ GUID }) => child.GUID == GUID);
                        if (!isEqual(old, child)) {
                          //获取修改了什么
                          Object.keys(child).forEach((key) => {
                            const newValue = child[key];
                            const oldValue = old[key];
                            if (
                              (!newValue && !oldValue && newValue !== 0 && oldValue !== 0) ||
                              removeFields.includes(key)
                            )
                              return;
                            if (newValue != oldValue && fields.includes(key)) {
                              newChangeForm[key] = newValue;
                              oldChangeForm[key] = oldValue;
                            }
                          });
                          if (
                            JSON.stringify(newChangeForm) !== '{}' ||
                            JSON.stringify(oldChangeForm) !== '{}'
                          ) {
                            changed.push({
                              ...newChangeForm,
                              state: 'modified',
                              GUID: child.GUID,
                            });
                            oldList.push(old);
                          }
                        }
                      }
                    }
                  }
                  const subList = [...removed, ...added, ...changed];
                  if (removed.length) {
                    const tabNames = ['eGridZwjjInfo', 'eGridZwjjBack', 'eGridZwjjRate'];
                    const lists: Recordable = [];
                    tabNames.forEach((key) => {
                      lists.push(...get(memory, key, []));
                    });
                    removed.forEach(({ GUID }) => {
                      oldList.push({
                        ...lists.find((i) => i.GUID == GUID),
                      });
                    });
                  }
                  if (subList.length) {
                    const info = {
                      subList,
                      oldList,
                      userName: store.get('user', 'userInfo').nickName,
                      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                    };
                    changeInfo = JSON.stringify(info);
                  }
                }
              } else if (['pZwjjCapital', 'pZwjjInterest'].includes(tabType)) {
                const fields = [...zwjjCapitalTableFields, ...zwjjInterestTableFields].map(
                  (i) => i.field,
                );
                const others = {
                  eGridZwjjCapital: 6, // 偿还本金
                  eGridZwjjInterest: 7, // 罚息
                };
                const oldList: Recordable[] = [];
                const subList: Recordable[] = [];

                for (const key of Object.keys(others)) {
                  const list = get(origin, key, []);
                  const bak = get(memory, key, []);
                  const removed = bak
                    .filter(({ GUID }) => list.findIndex((it) => it.GUID == GUID) < 0)
                    .map((it) => ({ GUID: it.GUID, state: 'removed' }));
                  const changed: Recordable[] = [];
                  const added: Recordable[] = [];
                  for (const now of list) {
                    const val = omit(now, ['id']);
                    if (isEmpty(val)) continue;
                    const extra = { CTYPE: others[key], DEBTGUID: GUID };
                    if (!val.GUID) {
                      const cid = await http.get({ url: '/lpzw/czDebt/getSubGuid' });
                      added.push({ ...val, ...extra, state: 'added', GUID: cid });
                      continue;
                    }
                    const old = bak.find(({ GUID }) => val.GUID == GUID);
                    if (isEqual(val, old)) continue;
                    const oldChangeForm = {};
                    const newChangeForm = {};
                    if (!isEqual(old, val)) {
                      //获取修改了什么
                      Object.keys(val).forEach((key) => {
                        const newValue = val[key];
                        const oldValue = old[key];
                        if (!newValue && !oldValue && newValue !== 0 && oldValue !== 0) return;
                        if (newValue != oldValue && fields.includes(key)) {
                          newChangeForm[key] = newValue;
                          oldChangeForm[key] = oldValue;
                        }
                      });
                      if (
                        JSON.stringify(newChangeForm) !== '{}' ||
                        JSON.stringify(oldChangeForm) !== '{}'
                      ) {
                        changed.push({
                          ...extra,
                          ...newChangeForm,
                          state: 'modified',
                          GUID: val.GUID,
                        });
                        oldList.push(old);
                      }
                    }
                    // changed.push({ ...val, ...extra, state: 'modified', GUID: val.GUID });
                  }

                  subList.push(...removed, ...added, ...changed);
                  if (removed.length) {
                    const tabNames = ['eGridZwjjCapital', 'eGridZwjjInterest'];
                    const lists: Recordable = [];
                    tabNames.forEach((key) => {
                      lists.push(...get(memory, key, []));
                    });
                    console.log(lists, removed, memory);

                    removed.forEach(({ GUID }) => {
                      oldList.push({
                        ...lists.find((i) => i.GUID == GUID),
                      });
                    });
                  }
                }
                if (subList.length) {
                  const info = {
                    subList,
                    oldList,
                    userName: store.get('user', 'userInfo').nickName,
                    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                  };
                  changeInfo = JSON.stringify(info);
                }
              }
              if (changeInfo) {
                await http.post({
                  url: '/lpzw/debtChange/insertChange',
                  data: {
                    changeInfo,
                    type: tabType,
                    status: 1,
                    debtGuid: GUID,
                  },
                });
                close(true);
              } else {
                close();
              }
            },
          };
          const fields = {
            zwjjBaseFields,
            zwjjInfoTableFields,
            zwjjBackTableFields,
            zwjjRateTableFields,
            zwjjCapitalTableFields,
            zwjjInterestTableFields,
          };
          const slots = {
            title: () => [h(borrChange, { tabType, checkRow: row, fields })],
          };
          open({ inner, layout, modal, slots, transfer });
        },
        ifShow: function (_, { row: { CHANGE_GUID } }, { transfer }) {
          return transfer.bgAdmin && !CHANGE_GUID;
        },
      },
    },
  },
];

const bGridCommonEdit: Recordable[] = [
  {
    name: 'add',
    label: '增加',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:plus-lg',
        onClick: (_, { rowIndex: index }, { me }, { dc: { update } }) =>
          update({ path: me, action: 'add', index: index + 1, value: {} }),
      },
    },
  },
  {
    name: 'del',
    label: '删除',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:trash3',
        ifShow: (_, { row, $grid }) => $grid.getTableData().fullData.length > 1 || row.MONEY1,
        popConfirm: {
          title: '是否确认删除',
          confirm: async (_0, { rowIndex: index }, { me }, { dc: { update } }) =>
            update({ path: me, action: 'del', index }),
        },
      },
    },
  },
];

const zwjjBaseFields: Recordable[] = [
  {
    field: 'FINANCE_NATIONAL_GUID',
    title: '融资备案Guid',
    component: 'Input',
    visible: false,
    ui: {},
  },
  {
    field: 'FINANCE_NATIONAL.name',
    title: '融资备案',
    component: 'Input',
    required: true,
    ui: {
      // self: {
      //   colProps: { span: 24 },
      // },
      props: {
        readonly: true,
        onClick: async (
          _,
          { origin, me, control },
          { dc: { open, close, update }, xe: { get, set } },
        ) => {
          const ENTERPRISEGUID = get(origin, `${me}.ENTERPRISEGUID`, '');
          const ret: any = await new Promise((resolve) => {
            const inner = {
              onCancel: async (e, { memory }) => {
                delete memory.modal;
              },
              onOk: async () => close(),
              afterClose: async ({ memory }, { xe }) => {
                const _ret = xe.get(memory, 'modal', false);
                delete memory.modal;
                resolve(_ret);
              },
            };
            const layout = { id: 'pZwrzbaSM' };
            const modal = {
              title: '选择融资备案',
              width: '75vw',
              // height: document.body.clientHeight * 0.75,
              minHeight: document.body.clientHeight * 0.75,
              destroyOnClose: false,
              centered: true,
              // destroyOnClose: true,
              open: true,
            };
            const transfer = { ENTERPRISEGUID };
            open({ inner, layout, modal, transfer });
          });
          if (!ret) return;
          const {
            guid,
            enterpriseName,
            enterpriseGuid,
            name,
            itemGuid,
            money,
            applyDate,
            institutionCode,
            // institutionName,
            isInner,
            typeCode,
            // typeName,
            rate,
            month,
          } = ret;
          const BMONEY = get(origin, `${me}.BMONEY`, 0);
          const EXRATE = get(origin, `${me}.EXRATE`, 1);
          update({
            path: me,
            value: {
              FINANCE_NATIONAL_GUID: guid,
              'FINANCE_NATIONAL.name': name,
              ENTERPRISEGUID: enterpriseGuid,
              ENTERPRISE: enterpriseName,
              ITEMNAME: name,
              ITEMGUID: itemGuid,
              AGREEMONEY: money,
              AGREERMBMONEY: money * EXRATE,
              BMONEY,
              PMONEY: money - BMONEY,
              BOOKDATE: applyDate,
              LOANER: institutionCode || '',
              IS_INNER: isInner || '',
              PPPMODE: typeCode || '',
              YEARRATE: rate,
              DEBTTERM: month,
            },
          });
          set(
            control,
            'page.pZwjjInvestor.show',
            ['01', '02', '04', '06', '07', '20', '99'].indexOf(typeCode) < 0,
          );
        },
        suffix: '•••',
      },
    },
  },
  enterpriseFormField,
  debtcodeFormField,
  {
    field: 'RESTMONEY',
    title: '债务余额',
    component: 'InputNumber',
    disable: true,
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / 10000, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * 10000,
        };
      },
    },
  },
  // {
  //   field: 'DEBTENTERPRISE',
  //   title: '批准举债融资的单位名称',
  //   component: 'Input',
  //   required: true,
  //   ui: {},
  // },
  {
    field: 'ENABLED',
    title: '',
    component: 'Input',
    required: false,
    visible: false,
    defaultValue: 1,
    ui: {},
  },
  {
    field: 'EXAMSTATE',
    title: '',
    component: 'Input',
    required: false,
    visible: false,
    defaultValue: 30,
    ui: {},
  },
  {
    field: 'DEBTLEADER',
    title: '批准举债融资的单位领导人姓名',
    component: 'Input',
    required: false,
    visible: false,
    defaultValue: '01',
    ui: {},
  },
  merge(getPMode(), {
    field: 'PPPMODE',
    title: '融资模式',
    required: true,
    ui: {
      props: {
        onChange: (value, ...extra) => {
          const [{ xe }, { control }] = extra.reverse();
          const isShowInvestor = ['01', '02', '04', '06', '07', '20', '99'].indexOf(value) < 0;
          xe.set(control, 'page.pZwjjInvestor.show', isShowInvestor);
        },
      },
    },
  }),
  {
    field: 'GUARANTEE_WAY',
    title: '保证方式',
    required: true,
    component: 'ApiSelect',
    defaultValue: '00',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo2', data: { BMTYPE: 12 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        onChange: (value, ...extra) => {
          const [{ xe }, { control }] = extra.reverse();
          xe.set(control, 'page.pZwjjDiya.show', ['01', '04', '05', '07'].indexOf(value) > -1);
          xe.set(control, 'page.pZwjjZhiya.show', ['02', '04', '06', '07'].indexOf(value) > -1);
          xe.set(control, 'page.pZwjjDanbao.show', ['03', '05', '06', '07'].indexOf(value) > -1);
        },
      },
    },
  },
  {
    field: 'ISADVANCE',
    title: '是否可提前还款',
    required: true,
    component: 'ApiSelect',
    defaultValue: '0',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const data = { type: 4, BMTYPE: 16 };
          return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
      self: { colProps: { pull: 16, offset: 16 } },
    },
  },
  {
    field: 'NAME',
    title: '债务名称',
    component: 'Input',
    required: true,
    ui: {},
  },
  {
    field: 'DEBTTYPE',
    title: '债务类别',
    required: true,
    component: 'ApiTreeSelect',
    ui: {
      props: ({ formActionType: { clearValidate } }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        const { mapTree, toArrayTree } = lib.xe;
        const treeData: any[] = [];
        return {
          api: async () => {
            const nodes: any[] = mapTree(
              toArrayTree(
                await http.form({
                  url: '/lpzw/czItem/listItemCombo',
                  data: { type: 3, BMTYPE: 18 },
                }),
                { parentKey: 'pid' },
              ),
              (item) => ({ ...item, disabled: item.children && item.children.length > 0 }),
            );
            treeData.splice(0, treeData.length, ...nodes);
            return treeData;
          },
          labelField: 'text',
          valueField: 'id',
          immediate: true,
          showSearch: true,
          treeNodeFilterProp: 'text',
          onChange: () => {
            clearValidate('ITEMNAME');
          },
        };
      },
    },
  },
  {
    field: 'BOOKDATE',
    title: '签订日期',
    component: 'DatePicker',
    required: true,
    ui: { props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    field: 'AGREENO',
    title: '协议号',
    component: 'Input',
    required: true,
    ui: {},
  },
  {
    field: 'ITEMNAME',
    fields: ['ITEMGUID'],
    title: '建设项目',
    component: 'Input',
    ui: {
      props: {
        readonly: true,
        onClick: async (
          _,
          { origin, me },
          { dc: { open, close, update, message }, xe: { get } },
        ) => {
          const ENTERPRISEGUID = get(origin, `${me}.ENTERPRISEGUID`, '');
          if (!ENTERPRISEGUID) return message.error('请先选择债务单位');
          const ret: any = await new Promise((resolve) => {
            const inner = {
              onCancel: async (e, { memory }) => {
                delete memory.modal;
              },
              onOk: async () => close(),
              afterClose: async ({ memory }, { xe }) => {
                const _ret = xe.get(memory, 'modal', false);
                delete memory.modal;
                resolve(_ret);
              },
            };
            const layout = { id: 'pZwxmS' };
            const modal = {
              title: '选择项目',
              width: '60vw',
              height: 600,
              minHeight: 600,
              defaultFullscreen: false,
              // destroyOnClose: true,
              open: true,
            };
            const transfer = { ENTERPRISEGUID };
            open({ inner, layout, modal, transfer });
          });
          if (!ret) return;
          const { GUID, NAME } = ret;
          update({ path: 'eFormZwjjBase', value: { ITEMNAME: NAME, ITEMGUID: GUID } });
        },
        suffix: '•••',
      },
    },
  },
  {
    field: 'DEBTTERM',
    title: '债务期限(月)',
    required: true,
    component: 'InputNumber',
    ui: {
      props: { keyboard: true, min: 0, step: 10 },
    },
  },
  {
    field: '',
    component: 'Divider',
    title: '',
    ui: { self: { colProps: { span: 24 } } },
  },
  {
    field: 'OLD_DEBT_TYPE',
    title: '债务类型',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const data = { type: 3, BMTYPE: 52 };
          return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  },
  {
    field: 'INTEREST_WAY',
    title: '结息方式',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo2', data: { BMTYPE: 10 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
      self: { colProps: { pull: 8, offset: 8 } },
    },
  },
  {
    field: 'LOANTYPE',
    title: '债权类型',
    component: 'ApiTreeSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { mapTree, toArrayTree } = lib.xe;
          const { http } = lib.dc;
          const nodes: any[] = mapTree(
            toArrayTree(
              await http.form({
                url: '/lpzw/czItem/listItemCombo',
                data: { type: 3, BMTYPE: 19 },
              }),
              { parentKey: 'pid' },
            ),
            (item) => ({ ...item, disabled: item.children && item.children.length > 0 }),
          );
          return nodes;
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
    },
  },
  {
    field: 'LOANER',
    title: '债权人',
    component: 'ApiTreeSelect',
    required: true,
    ui: {
      props: ({ formModel, formActionType: { clearValidate } }, ...args) => {
        const [{ me, memory }, { dc, xe }] = args.slice(-2);
        const { http } = dc;
        const { findTree, get, mapTree, set, toArrayTree } = xe;
        const optionKey = `options.${me}.loaner`;
        return {
          api: async () => {
            const nodes: any[] = mapTree(
              toArrayTree(
                await http.form({
                  url: '/lpzw/czItem/listItemCombo',
                  data: { type: 3, BMTYPE: 28 },
                }),
                { parentKey: 'pid' },
              ),
              (item) => ({ ...item, disabled: item.children && item.children.length > 0 }),
            );
            set(memory, optionKey, nodes);
            return nodes;
          },
          labelField: 'text',
          valueField: 'id',
          immediate: true,
          showSearch: true,
          treeNodeFilterProp: 'text',
          onChange: (value, labels) => {
            const treeData = get(memory, optionKey, []);
            const node = findTree(treeData, ({ id }) => `${id}` == `${value}`);
            if (!node) return;
            const { item } = node;
            formModel.IS_INNER = `${item.INTERFACEID}` === '1' ? '1' : '0';
            clearValidate('IS_INNER');
            console.log('change: ', value, labels, item);
          },
        };
      },
    },
  },
  {
    field: 'LOANERFULLNAME',
    title: '债权人全称',
    component: 'Input',
    required: true,
    ui: {},
  },
  {
    field: 'IS_INNER',
    title: '债权人范围',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: ({ formModel }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        return {
          api: async () =>
            await http.form({
              url: '/lpzw/czItem/listBMCombo2',
              data: { BMTYPE: 11 },
            }),
          labelField: 'text',
          valueField: 'id',
          immediate: true,
          onChange: (value) => {
            if (value !== `${value}`) formModel['IS_INNER'] = `${value}`;
          },
        };
      },
    },
  },
  {
    field: '',
    component: 'Divider',
    title: '',
    ui: { self: { colProps: { span: 24 } } },
  },
  {
    field: 'BMONEY',
    fields: ['PMONEY'],
    defaultValue: 0,
    visible: false,
    ui: {},
  },
  {
    field: 'AGREEMONEY',
    title: '协议金额(本位币)',
    component: 'InputNumber',
    required: true,
    defaultValue: 0,
    ui: {
      props: ({ formModel }, ...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          keyboard: true,
          step: 10 * unit,
          addonAfter: '万',
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
          onChange: (value) => (
            (formModel.AGREERMBMONEY = value * formModel.EXRATE),
            (formModel.PMONEY = value - formModel.BMONEY)
          ),
        };
      },
    },
  },
  {
    field: 'BMONEY',
    title: '已提款金额',
    component: 'Input',
    visible: false,
    ui: {},
  },
  {
    field: 'CURRENCY',
    title: '币种',
    component: 'ApiSelect',
    required: true,
    defaultValue: 'CNY',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo', data: { BMTYPE: 1 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: 'EXRATE',
    title: '汇率',
    component: 'InputNumber',
    required: true,
    defaultValue: 1,
    ui: {
      props: ({ formModel }) => {
        return {
          keyboard: true,
          min: 0,
          step: '0.01',
          stringMode: true,
          formatter: (value) => {
            const reg1 = `${value}`.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            return reg1.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
          },
          onChange: (value) => {
            formModel.CREDITMONEY1 = value * formModel.CREDITMONEY;
            formModel.AGREERMBMONEY = value * formModel.AGREEMONEY;
          },
        };
      },
    },
  },
  {
    field: 'AGREERMBMONEY',
    title: '协议金额(RMB)',
    component: 'InputNumber',
    disable: true,
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'CREDITMONEY',
    title: '授信额度(本位币)',
    component: 'InputNumber',
    required: true,
    defaultValue: 0,
    ui: {
      props: ({ formModel }, ...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          keyboard: true,
          min: 0,
          step: 10 * unit,
          addonAfter: '万',
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
          onChange: (value) => (formModel.CREDITMONEY1 = value * formModel.EXRATE),
        };
      },
    },
  },
  {
    field: 'CREDIT_PERIOD_DATE',
    title: '授信有效期至',
    component: 'DatePicker',
    required: true,
    ui: { props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    field: 'CREDITMONEY1',
    title: '授信额度(RMB)',
    component: 'InputNumber',
    disable: true,
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: '',
    component: 'Divider',
    title: '',
    ui: { self: { colProps: { span: 24 } } },
  },
  {
    field: 'RATETYPE',
    title: '利率类型',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 4, BMTYPE: 20 },
          });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: 'PLEDGE_ENTERPRISE',
    title: '定价基础利率',
    component: 'ApiSelect',
    ui: {
      props: ({ formModel }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        return {
          api: async () => {
            const data = { type: 4, BMTYPE: 56 };
            return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          },
          labelField: 'text',
          valueField: 'id',
          immediate: true,
          onChange: () => delete formModel.FLOAT_LEVEL,
        };
      },
    },
  },
  {
    field: 'FLOAT_LEVEL',
    title: '计息档次',
    component: 'ApiSelect',
    ui: {
      props: ({ formModel }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        const params = { INTERFACEID: formModel['PLEDGE_ENTERPRISE'] };
        return {
          api: async () => {
            const data = { type: 4, BMTYPE: 57, ...params };
            return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          },
          params,
          labelField: 'text',
          valueField: 'id',
          immediate: true,
        };
      },
    },
  },
  {
    field: 'FLOATMODE',
    title: '利率浮动方式',
    component: 'Select',
    visible: false,
    ui: {
      props: {
        options: floatModeOptions,
        labelField: 'text',
        valueField: 'id',
      },
    },
  },
  {
    field: 'RATE_FLOAT_CYCLE',
    title: '债务利率浮动周期',
    component: 'ApiSelect',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo2', data: { BMTYPE: 14 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: 'PLEDGE_DATE',
    title: '首次调整日期',
    component: 'DatePicker',
    ui: {
      props: ({ formModel }, _, { dayjs }) => {
        return {
          valueFormat: 'YYYY-MM-DD',
          onChange: (value) => {
            console.log('PLEDGE_DATE change: ', value !== `${value}`, value);
            if (value !== `${value}`) formModel['PLEDGE_DATE'] = dayjs(value).format('YYYY-MM-DD');
          },
        };
      },
    },
  },
  {
    field: 'PLEDGE_MONEY',
    title: '加/减点数',
    component: 'InputNumber',
    defaultValue: 0,
    ui: {
      props: { keyboard: true, min: 0, step: 10, addonAfter: 'BP' },
    },
  },
  {
    field: 'FIXEDRATE',
    title: '利率(%)',
    component: 'InputNumber',
    defaultValue: 0,
    ui: {
      props: { keyboard: true, min: 0, step: 0.05, precision: 2 },
      self: { colProps: { pull: 8, offset: 8 } },
    },
  },
  {
    field: 'YEARRATE',
    title: '年费率(%)',
    component: 'InputNumber',
    defaultValue: 0,
    ui: {
      props: { keyboard: true, min: 0, step: 10, precision: 2 },
    },
  },
  {
    field: 'COMPLEXRATE',
    title: '审批综合利率(%)',
    component: 'InputNumber',
    defaultValue: 0,
    ui: {
      props: { keyboard: true, min: 0, step: 0.05, precision: 2 },
    },
  },
  {
    field: 'PLEDGE_REMARK',
    title: '审批备案文号',
    component: 'Input',
    ui: {},
  },
  {
    field: '',
    component: 'Divider',
    title: '',
    ui: { self: { colProps: { span: 24 } } },
  },
  {
    field: 'REMARK',
    title: '备注',
    component: 'InputTextArea',
    ui: { self: { colProps: { span: 24 } } },
  },
];

const zwjjDiyaTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'AMOUNTTEXT',
    component: 'Input',
    title: '抵押物',
    ui: { self: { minWidth: 140 } },
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'Input',
    title: '其他单位资产',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'ApiTreeSelect',
    title: '资产类别',
    ui: {
      self: { minWidth: 140 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR3',
    component: 'ApiTreeSelect',
    title: '抵押类型',
    ui: {
      self: { minWidth: 140 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '抵押物原值',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '抵押物现值（评估价）',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY3',
    component: 'InputNumber',
    title: '抵押金额',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '抵押率/%',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjZhiyaTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'STR4',
    component: 'ApiTreeSelect',
    title: '标的物所属单位（系统内）',
    ui: {
      self: { minWidth: 200 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'Input',
    title: '标的物所属单位（系统外）',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '质押到期日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'Input',
    title: '质押物名称',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'STR3',
    component: 'ApiTreeSelect',
    title: '质押类型',
    ui: {
      self: { minWidth: 180 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '质押物金额（人民币）',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE2',
    component: 'InputNumber',
    title: '利率/%',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '质押物现值（评估价）',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY3',
    component: 'InputNumber',
    title: '质押金额',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '质押率/%',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjDanbaoTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'STR1',
    component: 'ApiTreeSelect',
    title: '集团内担保单位',
    ui: {
      self: { minWidth: 200 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR4',
    component: 'ApiTreeSelect',
    title: '集团间担保单位',
    ui: {
      self: { minWidth: 200 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'Input',
    title: '集团外担保单位',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'STR3',
    component: 'Input',
    title: '担保单位统一社会信用代码',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '担保金额',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '担保费率/%',
    ui: { self: { minWidth: 120 } },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '担保年费用',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY3',
    component: 'InputNumber',
    title: '一次性担保费用',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjInfoTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '提款日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '提款金额(原币)',
    ui: {
      self: {
        minWidth: 120,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '汇率',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '提款金额(人民币)',
    ui: {
      self: {
        minWidth: 132,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'ApiTreeSelect',
    title: '偿还资金来源',
    ui: {
      self: { minWidth: 125 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'Input',
    title: '提款凭证号',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'DATE2',
    component: 'Input',
    visible: false,
    title: '截止日期',
    ui: { self: { minWidth: 140 } },
  },
  {
    parent: 0,
    field: 'DATE3',
    component: 'DatePicker',
    title: '记账日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjBackTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'AMOUNT',
    visible: false,
    title: '举借ID',
    ui: {
      self: {
        minWidth: 140,
        filters: [{ data: '' }],
        filterMethod: ({ option, row }) => row.AMOUNT == option.data,
      },
      custom: {
        isInputFilter: true,
      },
    },
  },
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '计划偿还日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '计划偿还金额(RMB)',
    align: 'right',
    ui: {
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'Input',
    title: '展期合同号',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'DATE2',
    component: 'DatePicker',
    title: '展期后还款日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'ApiSelect',
    title: '定价基准利率时间',
    ui: {
      self: { minWidth: 160 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        'onUpdate:value': async (val, { $grid }, _, { dc: { http }, xe: { get, set } }) => {
          if (!val) return;
          const opKey = `params.options.${val}`;
          const str3TypeColumn = $grid.getColumnByField('STR3');
          const options = get(str3TypeColumn, opKey, []);
          if (options.length > 0) return;
          const ret: any = await http.form({ url: '/lpzw/cas/getRateSub', data: { id: val } });
          set(str3TypeColumn, opKey, ret);
        },
      },
      slots: {
        default: ({ column, row }, _, { xe: { get } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const option = get(column, 'params.options', []).find((it) => it.id == row[field]);
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR3',
    component: 'ApiSelect',
    title: '定价基准利率',
    ui: {
      self: { minWidth: 200 },
      props: {
        api: async (_0, { row, column }, _, { xe: { get } }) =>
          get(column, `params.options.${row.STR2}`, []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
      },
      slots: {
        default: ({ column, row }, _, { xe: { get } }) => {
          const field = column.field;
          if (!row[field]) return '';
          if (!row.STR2) return '';
          const opKey = `params.options.${row.STR2}`;
          const option = get(column, opKey, []).find((it) => it.id == row[field]);
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjRateTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'AMOUNT',
    visible: false,
    title: '举借ID',
    ui: {
      self: {
        minWidth: 140,
        filters: [{ data: '' }],
        filterMethod: ({ option, row }) => row.AMOUNT == option.data,
      },
      custom: {
        isInputFilter: true,
      },
    },
  },
  {
    parent: 0,
    field: 'AMOUNTTEXT',
    component: 'Input',
    title: '举借信息',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '应付日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '应付利息',
    ui: {
      self: {
        minWidth: 120,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjRateEditFields: Recordable[] = [
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '应付日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '应付利息',
    ui: {
      self: {
        minWidth: 120,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    align: 'right',
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjCapitalTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'AMOUNTTEXT',
    component: 'ApiSelect',
    title: '还款计划日期',
    ui: {
      self: { minWidth: 180 },
      props: {
        api: async (_0, a, _, { xe: { get } }) => {
          const { data, column, row } = a;
          const ids = data.map(({ AMOUNT }) => AMOUNT);
          console.log('open AMOUNTTEXT', a, get(column, 'params.options', []));
          return get(column, 'params.options', []).filter(
            ({ AMOUNT }) => row.AMOUNT == AMOUNT || ids.indexOf(AMOUNT) < 0,
          );
        },
        labelField: 'AMOUNTTEXT',
        valueField: 'AMOUNTTEXT',
        immediate: true,
        allowClear: true,
        'onUpdate:value': async (val, { $grid, row }, _, { xe: { get, omit, set } }) => {
          console.log('AMOUNTTEXT change: ', val);
          if (!val) return;
          const txtColumn = $grid.getColumnByField('AMOUNTTEXT');
          const options = get(txtColumn, 'params.options', []);
          const value = options.find((it) => `${it.AMOUNTTEXT}` == `${val}`);
          Object.keys(omit(value, ['id'])).forEach((key) => set(row, key, value[key]));
        },
      },
      slots: {
        default: ({ column, row }, _, { xe: { get } }) => {
          const field = 'AMOUNT';
          if (!row[field]) return '';
          const option = get(column, 'params.options', []).find((it) => it.AMOUNT == row[field]);
          if (!option) return '';
          return option.AMOUNTTEXT;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '偿还日期',
    ui: {
      self: { minWidth: 140 },
      props: {
        valueFormat: 'YYYY-MM-DD',
        onChange: function (
          _,
          _01,
          { row },
          { transfer: { maxReportMonth }, me },
          { dc: { message, update } },
        ) {
          const DATE1 = row.DATE1;
          if (DATE1 && maxReportMonth && !timeIsConform(maxReportMonth, DATE1)) {
            update({ action: 'edit', id: row['id'], value: { ...row, DATE1: '' }, path: me });
            return message.warn(
              `该单位${maxReportMonth}数据已上报,请选择提款日期在这之后的时间,或联系管理员`,
            );
          }
        },
      },
    },
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'ApiTreeSelect',
    title: '偿还资金来源',
    ui: {
      self: { minWidth: 125 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '还款金额(原币)',
    ui: {
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
        onChange: function (_, { row }, { me }, { dc: { update } }) {
          const money = row.MONEY1;
          const rate = row.RATE;
          update({
            action: 'edit',
            id: row['id'],
            value: { ...row, MONEY2: money * rate },
            path: me,
          });
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '汇率',
    ui: {
      self: { minWidth: 120 },
      props: {
        onChange: function (_, { row }, { me }, { dc: { update } }) {
          const money = row.MONEY1;
          const rate = row.RATE;
          update({
            action: 'edit',
            id: row['id'],
            value: { ...row, MONEY2: money * rate },
            path: me,
          });
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '偿还金额(人民币)',
    disable: true,
    ui: {
      self: {
        minWidth: 180,
        formatter: ({ row }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          const money = get(row, 'MONEY1', 0) * get(row, 'RATE', 1);
          return commafy(toNumber(money / unit), { digits: 4 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'Input',
    title: '会计凭证号',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'DATE3',
    component: 'DatePicker',
    title: '记账日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
];

const bGridCapitalTableEdit: Recordable[] = [
  {
    name: 'add',
    label: '增加',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:plus-lg',
        onClick: (_, { rowIndex: index }, { me }, { dc: { update } }) =>
          update({ path: me, action: 'add', index: index + 1, value: {} }),
      },
    },
  },
  {
    name: 'del',
    label: '删除',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:plus-lg',
        ifShow: (_, { row, $grid }, { transfer }) => {
          if (
            transfer.maxReportMonth &&
            row.DATE1 &&
            !timeIsConform(transfer.maxReportMonth, row.DATE1)
          ) {
            return false;
          } else {
            return $grid.getTableData().fullData.length > 1 || row.AMOUNTTEXT;
          }
        },
        popConfirm: {
          title: '是否确认删除',
          confirm: async (_0, { rowIndex: index }, { me }, { dc: { update } }) =>
            update({ path: me, action: 'del', index }),
        },
      },
    },
  },
];
const zwjjInterestTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'DATE1',
    component: 'DatePicker',
    title: '支付日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'STR1',
    component: 'Input',
    title: '利息/罚息',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'ApiTreeSelect',
    title: '偿还资金来源',
    ui: {
      self: { minWidth: 200 },
      props: {
        api: async (_0, { column }, _, { xe: { get } }) => get(column, 'params.options', []),
        labelField: 'text',
        valueField: 'id',
        allowClear: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
      slots: {
        default: ({ column, row }, _, { xe: { get, findTree } }) => {
          const field = column.field;
          if (!row[field]) return '';
          const ret = findTree(get(column, 'params.options', []), (it) => it.id == row[field]);
          if (!ret) return '';
          const { item: option } = ret;
          if (!option) return '';
          return option.text;
        },
      },
    },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '支付利息罚息(原币)',
    ui: {
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'RATE',
    component: 'InputNumber',
    title: '汇率',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '支付利息罚息(人民币)',
    ui: {
      self: {
        minWidth: 180,
        formatter: ({ cellValue }, { origin }, { xe: { commafy, get, toNumber } }) => {
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
            /(?:\.0*|(\.\d+?)0+)$/,
            '$1',
          );
        },
      },
      props: {
        addonAfter: '万',
        formatter: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { commafy, get } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
        },
        parser: (value, ...args) => {
          const [{ origin }, lib] = args.slice(-2);
          const { get, toNumber } = lib.xe;
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          return toNumber(value.replace(',', '')) * unit;
        },
      },
      custom: {
        summary: (arr, field, { origin }, { xe: { get, sum } }) =>
          sum(arr, field) / get(origin, 'eFormDefMoneyUnit._.unit', 1),
      },
    },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'DATE3',
    component: 'DatePicker',
    title: '记账日期',
    ui: { self: { minWidth: 140 }, props: { valueFormat: 'YYYY-MM-DD' } },
  },
  {
    parent: 0,
    field: 'STR3',
    component: 'Input',
    title: '会计凭证号',
    ui: { self: { minWidth: 120 } },
  },
  {
    parent: 0,
    field: 'MEMO',
    component: 'Input',
    title: '备注',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjInvestorTableFields: Recordable[] = [
  {
    parent: 0,
    field: 'STR1',
    component: 'Input',
    title: '实际投资者名称',
    ui: { self: { minWidth: 200 } },
  },
  {
    parent: 0,
    field: 'MONEY1',
    component: 'InputNumber',
    title: '区内机构实际投债额度',
    ui: { self: { minWidth: 140 } },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'MONEY2',
    component: 'InputNumber',
    title: '区外机构实际投债额度',
    ui: { self: { minWidth: 140 } },
    summary: 'sum',
  },
  {
    parent: 0,
    field: 'STR2',
    component: 'Input',
    title: '承销机构区外引资贡献',
    ui: { self: { minWidth: 200 } },
  },
];
const zwjjEditButtons: Recordable[] = [
  {
    name: 'add',
    label: '增加',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:plus-lg',
        ifShow: (
          _,
          { $grid, row, rowIndex },
          { transfer, origin },
          { xe: { get, sum, pluck, toNumber } },
        ) => {
          const isReadonlyCom = getIsReadonlyByActiveKey(transfer, 'pZwjjInfo');
          if (isReadonlyCom) return false;
          const need = toNumber(get(origin, 'eFormZwjjBase.AGREEMONEY', 0));
          const gridData = get(origin, 'eGridZwjjInfo');
          const total = sum(pluck(gridData, 'MONEY1'));
          if (need <= 0) return false;
          if (need <= total) return false;
          return rowIndex + 1 === $grid.getData().length && (row.MONEY1 > 0 || row.DATE1);
        },
        onClick: async (_, { rowIndex: index, row }, data, unitl) => {
          const { me } = data;
          const {
            dc: { update, next },
            $grid,
            xe: { uniqueId },
          } = unitl;
          await update({
            path: me,
            action: 'add',
            index: index + 1,
            value: { _id: uniqueId(row.id) },
          });
          await next();
          const editBtn = zwjjEditButtons.find((i) => i.name === 'edit');
          editBtn?.ui.props.onClick(_, { row: $grid.getData(index + 1) }, data, unitl);
        },
      },
    },
  },
  {
    name: 'edit',
    label: '编辑',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:pencil-square',
        ifShow: function (_, { row }, { transfer }) {
          if (
            transfer.maxReportMonth &&
            row.DATE1 &&
            !timeIsConform(transfer.maxReportMonth, row.DATE1)
          ) {
            return false;
          } else {
            return true;
          }
        },
        onClick: async (_, { row }, data, { xe, dc, $grid }) => {
          const {
            origin,
            transfer: { maxReportMonth },
          } = data;
          const { get, uniqueId, toNumber } = xe;
          const { open, update, message } = dc;
          const parent = origin;
          const AMOUNT = row['_id'] ?? row['GUID'];
          const id = row['id'];
          const subs = { eGridZwjjBack: 4, eGridZwjjRate: 5 };

          const ret: any = await new Promise((resolve) => {
            const _info = get(origin, 'eFormZwjjBase');
            const base = { ..._info, ...row };
            base.BMONEY = toNumber(_info.BMONEY) - toNumber(row.MONEY1);
            base.PMONEY = toNumber(_info.PMONEY) + toNumber(row.MONEY1);
            const remainEdit = Object.keys(subs).reduce((ret, key) => {
              ret[`${key}Edit`] = get(origin, key, []).filter(
                ({ AMOUNT }) => [row.GUID, row._id].indexOf(AMOUNT) < 0,
              );
              return ret;
            }, {});
            const subEdit = Object.keys(subs).reduce((ret, key) => {
              ret[`${key}Edit`] = get(origin, key, []).filter(
                ({ AMOUNT }) => [row.GUID, row._id].indexOf(AMOUNT) > -1,
              );
              return ret;
            }, {});
            const eGridZwjjCapital = get(origin, 'eGridZwjjCapital', []);
            const eFormZwjjDrawalMoney = Object.assign({}, base, row);
            const transfer = { eFormZwjjInfo: base, eFormZwjjDrawalMoney, ...subEdit };
            Object.assign(transfer, { eGridZwjjCapital });
            const inner = {
              onOk: async (_, { origin }, { xe: { get, sum, pluck }, dc: { close, validate } }) => {
                console.log('modal ok click: ', parent, update, origin);
                const validateRes = await validate();
                if (validateRes['eFormZwjjDrawalMoney'] !== true) return;
                const need = get(origin, 'eFormZwjjDrawalMoney.MONEY2', 0);
                const gridData = get(origin, 'eGridZwjjBackEdit');
                const total = sum(pluck(gridData, 'MONEY1'));
                if (need != total) return message.warn(`计划还款金额必须等于提款金额`);
                if (maxReportMonth) {
                  const monthDate = get(origin, 'eFormZwjjDrawalMoney.DATE1');
                  if (!timeIsConform(maxReportMonth, monthDate)) {
                    return message.warn(
                      `该单位${maxReportMonth}数据已上报,请选择提款日期在这之后的时间,或联系管理员`,
                    );
                  }
                }
                const row = {
                  ...get(origin, 'eFormZwjjDrawalMoney'),
                  MONEY2: need,
                  DATE3: '',
                  CTYPE: 3,
                };
                const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
                const AMOUNTTEXT = `${row.DATE1}|${row.MONEY1 / unit}`;
                const custom = { action: 'edit', id, value: row, path: 'eGridZwjjInfo' };
                update(custom);
                console.log('修改举借: ', row, subEdit);
                Object.keys(subs).map((key) => {
                  const editKey = `${key}Edit`;
                  const editData = get(origin, editKey);

                  editData.map((it) => {
                    const _id = it['GUID'] ?? it['_id'] ?? uniqueId(key);
                    Object.assign(it, { AMOUNT, AMOUNTTEXT, _id, CTYPE: subs[key] });
                  });
                  update({
                    path: key,
                    action: 'load',
                    value: [...remainEdit[editKey], ...editData],
                  });
                });
                close();
                setTimeout(() => {
                  $grid.updateFooter();
                }, 0);
                resolve(origin);
              },
            };
            const layout = { id: 'pZwjjInfoM' };
            const modal = {
              title: '举借信息(单位：万元)',
              width: '70vw',
              height: 700,
              minHeight: 700,
              defaultFullscreen: false,
              destroyOnClose: true,
              centered: true,
              open: true,
            };
            console.log('inner click: ', { inner, layout, modal, transfer });
            open({ inner, layout, modal, transfer });
          });
          console.log('modal ret', _, ret);
        },
      },
    },
  },
  {
    name: 'del',
    label: '删除',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:trash3',
        ifShow: function (_, { row }, { transfer }) {
          if (
            transfer.maxReportMonth &&
            row.DATE1 &&
            !timeIsConform(transfer.maxReportMonth, row.DATE1)
          ) {
            return false;
          } else {
            return true;
          }
        },
        popConfirm: {
          title: '是否确认删除',
          confirm: async (_, { rowIndex: index, row }, data, { xe, dc: { update } }) => {
            const { get } = xe;
            const { me, origin } = data;
            const subs = ['eGridZwjjBack', 'eGridZwjjRate'];
            subs.map((key) => {
              const child = get(origin, key, []);
              const remove = child.map(({ AMOUNT }, ind) =>
                [row._id, row.GUID].indexOf(AMOUNT) > -1 ? ind : -1,
              );
              remove
                .filter((_) => _ > -1)
                .reverse() // 反序从后面删除保证索引不变
                .map((pos) => update({ path: key, action: 'del', index: pos }));
            });
            update({ path: me, action: 'del', index });
          },
        },
      },
    },
  },
];

const zwjjInfoFields: Recordable[] = [
  {
    field: 'ENTERPRISE',
    fields: ['ENTERPRISEGUID'],
    title: '债务单位',
    disable: true,
    component: 'Input',
    ui: {},
  },
  {
    field: 'NAME',
    title: '债务名称',
    component: 'Input',
    disable: true,
    ui: {},
  },
  {
    field: 'AGREENO',
    title: '协议号',
    component: 'Input',
    disable: true,
    ui: {},
  },
  {
    field: 'AGREEMONEY',
    title: '协议金额',
    disable: true,
    component: 'InputNumber',
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'BMONEY',
    title: '已提款金额',
    disable: true,
    component: 'InputNumber',
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'PMONEY',
    title: '剩余提款金额',
    disable: true,
    component: 'InputNumber',
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: unit == 10000 ? '万' : '',
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
];
const zwjjDrawalMoneyFields: Recordable[] = [
  {
    field: 'DATE1',
    title: '提款日期',
    component: 'DatePicker',
    required: true,
    ui: {
      custom: { default: (_, { dayjs }) => dayjs().format('YYYY-MM-DD') },
      props: { valueFormat: 'YYYY-MM-DD' },
    },
  },
  {
    field: 'MONEY1',
    title: '提款金额',
    required: true,
    component: 'InputNumber',
    ui: {
      props: (...args) => {
        const [{ origin, transfer }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        const max = get(transfer, 'eFormZwjjInfo.PMONEY', 1);
        return {
          addonAfter: '万',
          max,
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'REPORT_MONEY',
    title: '上报省数据(RMB)',
    component: 'InputNumber',
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        return {
          addonAfter: '万',
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'RATE',
    title: '提款汇率',
    component: 'Input',
    disable: true,
    ui: {},
  },
  {
    field: 'MONEY2',
    title: '提款金额(RMB)',
    component: 'InputNumber',
    disable: true,
    ui: {
      props: (...args) => {
        const [{ origin }, lib] = args.slice(-2);
        const { commafy, get, toNumber } = lib.xe;
        const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
        const max = get(origin, 'eFormZwjjInfo.PMONEY');
        return {
          addonAfter: unit == 10000 ? '万' : '',
          max,
          step: 10 * unit,
          formatter: (value) =>
            commafy(value / unit, { digits: 6 }).replace(/(?:\.0*|(\.\d+?)0+)$/, '$1'),
          parser: (value) => toNumber(value.replace(',', '')) * unit,
        };
      },
    },
  },
  {
    field: 'STR1',
    title: '最终偿债资金来源',
    component: 'ApiTreeSelect',
    defaultValue: '02',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const { mapTree, toArrayTree } = lib.xe;
          const data = { type: 3, BMTYPE: 32 };
          const ret = await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          const nodes: any[] = mapTree(toArrayTree(ret, { parentKey: 'pid' }), (item) => ({
            ...item,
            disabled: item.children && item.children.length > 0,
          }));
          return nodes;
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
        showSearch: true,
        treeNodeFilterProp: 'text',
      },
    },
  },
  {
    field: 'STR2',
    title: '提款凭证号',
    component: 'Input',
    ui: {},
  },
  {
    field: 'DATE2',
    title: '还款截止日期',
    component: 'DatePicker',
    ui: {
      props: { valueFormat: 'YYYY-MM-DD' },
    },
  },
  {
    field: 'STR4',
    title: '付息方式',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo2', data: { BMTYPE: 10 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: 'RATE3',
    title: '放款综合利率/%',
    component: 'InputNumber',
    ui: {
      props: { keyboard: true, min: 0, step: 10, precision: 2 },
    },
  },
  {
    field: 'STR5',
    title: '利率类型',
    component: 'ApiSelect',
    required: true,
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          const data = { type: 4, BMTYPE: 20 };
          return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: '_gap',
    component: 'Divider',
    title: '',
    ui: {
      props: { style: 'border-block-start: transparent;' },
      self: { colProps: { span: 8 } },
    },
  },
  {
    field: 'STR6',
    title: '定价基础利率',
    component: 'ApiSelect',
    ui: {
      props: ({ formModel }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        return {
          api: async () => {
            const data = { type: 4, BMTYPE: 56 };
            return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          },
          labelField: 'text',
          valueField: 'id',
          immediate: true,
          onChange: () => delete formModel.STR7,
        };
      },
    },
  },
  {
    field: 'STR7',
    title: '计息档次',
    component: 'ApiSelect',
    ui: {
      props: ({ formModel }, ...args) => {
        const lib = args.slice(-1)[0];
        const { http } = lib.dc;
        const params = { INTERFACEID: formModel['STR6'] };
        return {
          api: async () => {
            const data = { type: 4, BMTYPE: 57, ...params };
            return await http.form({ url: '/lpzw/czItem/listItemCombo', data });
          },
          params,
          labelField: 'text',
          valueField: 'id',
          immediate: true,
        };
      },
    },
  },
  {
    field: '_gap',
    component: 'Divider',
    title: '',
    ui: {
      props: { style: 'border-block-start: transparent;' },
      self: { colProps: { span: 8 } },
    },
  },
  {
    field: 'STR8',
    title: '利率浮动方式',
    component: 'Select',
    defaultValue: '3',
    visible: false,
    ui: {
      props: {
        options: floatModeOptions,
        labelField: 'text',
        valueField: 'id',
      },
    },
  },
  {
    field: 'RATE_FLOAT_CYCLE',
    title: '债务利率浮动周期',
    component: 'ApiSelect',
    ui: {
      props: {
        api: async (...args) => {
          const lib = args.slice(-1)[0];
          const { http } = lib.dc;
          return await http.form({ url: '/lpzw/czItem/listBMCombo2', data: { BMTYPE: 14 } });
        },
        labelField: 'text',
        valueField: 'id',
        immediate: true,
      },
    },
  },
  {
    field: 'PLEDGE_DATE',
    title: '首次调整日期',
    component: 'DatePicker',
    ui: {
      props: ({ formModel }, _, { dayjs }) => {
        return {
          valueFormat: 'YYYY-MM-DD',
          onChange: (value) => {
            console.log('PLEDGE_DATE change: ', value !== `${value}`, value);
            if (value !== `${value}`) formModel['PLEDGE_DATE'] = dayjs(value).format('YYYY-MM-DD');
          },
        };
      },
    },
  },
  {
    field: 'RATE4',
    title: '加/减点数',
    component: 'InputNumber',
    ui: { props: { precision: 2, min: 0, addonAfter: 'BP' } },
  },
  {
    field: 'DATE5',
    title: '首次结息日期',
    component: 'DatePicker',
    ui: {
      props: ({ formModel }, _, { dayjs }) => {
        return {
          valueFormat: 'YYYY-MM-DD',
          onChange: (value) => {
            console.log('PLEDGE_DATE change: ', value !== `${value}`, value);
            if (value !== `${value}`) formModel['PLEDGE_DATE'] = dayjs(value).format('YYYY-MM-DD');
          },
        };
      },
    },
  },
  {
    field: 'RATE2',
    title: '利率(%)',
    required: true,
    component: 'InputNumber',
    ui: {
      props: { keyboard: true, min: 0, step: 10, precision: 2 },
    },
  },
  {
    field: 'MEMO',
    title: '提款备注',
    component: 'Input',
    ui: { self: { colProps: { span: 24 } } },
  },
];

const zwjjLPRSearchFields: Recordable[] = [
  {
    field: 'date',
    title: '年月',
    component: 'DatePicker',
    ui: {
      props: { picker: 'month', valueFormat: 'YYYY-MM' },
    },
  },
];
const zwjjLPRListFields: Recordable[] = [
  {
    field: 'year',
    title: '年份',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 100 } },
  },
  {
    field: 'month',
    title: '月份',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 80 } },
  },
  {
    field: 'inputDate',
    title: '创建时间',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 120 } },
  },
  {
    field: 'inputName',
    title: '创建人',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 160 } },
  },
  {
    field: 'editDate',
    title: '最近修改时间',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 120 } },
  },
  {
    field: 'editName',
    title: '最近修改人',
    component: 'Input',
    align: 'center',
    ui: { self: { minWidth: 160 } },
  },
];
const zwjjLPRFormButtons: Recordable[] = [
  {
    name: 'add',
    label: '新增',
    ui: {
      props: {
        preIcon: 'bi:plus-lg',
        class: 'mr-2',
      },
      events: {
        onClick: (_, { button, me, origin }, { dayjs, dc: { open }, xe: { get } }) => {
          const date = get(origin, `${me}.date`, dayjs().format('YYYY-MM'));
          const [year, month] = date.split('-');
          const transfer = {
            eFormZwjjLPREdit: { year, month, inputDate: dayjs().format('YYYY-MM-DD') },
          };
          const layout = { id: 'pZwjjLPRSet' };
          const modal = {
            title: '新增',
            width: '50vw',
            // height: document.body.clientHeight * 0.55,
            minHeight: document.body.clientHeight * 0.55,
            defaultFullscreen: false,
            destroyOnClose: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
          };
          const inner = {
            onOk: async (_, { origin }, { dc: { close, http, notification }, xe: { get } }) => {
              const inputDate = get(origin, `eFormZwjjLPREdit.inputDate`);
              const year = Number(get(origin, `eFormZwjjLPREdit.year`));
              const month = Number(get(origin, `eFormZwjjLPREdit.month`));
              const params = { inputDate, year, month, id: '' };
              const list = get(origin, 'eGridZwjjLPREdit', []);
              params['list'] = list.map((it, iId) => Object.assign({}, it, { id: null, iId }));
              await http.post({ url: '/lpzw/cas/saveRate', data: params });
              notification.success({ message: '定价基准利率添加成功', duration: 3 });
              close(true);
            },
          };
          console.log('inner click: ', button, { inner, layout, modal, transfer });
          open({ inner, layout, modal, transfer });
        },
      },
    },
  },
  {
    name: 'view',
    label: '查看',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:eye',
        onClick: async (_, { row }, data, { dc: { open } }) => {
          const transfer = { eFormZwjjLPREdit: row, isReadonly: true };
          const layout = { id: 'pZwjjLPRSet' };
          const modal = {
            title: '查看',
            width: '50vw',
            // height: document.body.clientHeight * 0.55,
            minHeight: document.body.clientHeight * 0.55,
            defaultFullscreen: false,
            destroyOnClose: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
          };
          const inner = {
            onOk: async (_, _2, { dc: { close } }) => {
              close(true);
            },
          };
          console.log('inner click: ', { inner, layout, modal, transfer });
          open({ inner, layout, modal, transfer });
        },
      },
    },
  },
  {
    name: 'edit',
    label: '修改',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:pencil-square',
        onClick: async (_, { row }, data, { dc: { open } }) => {
          const transfer = { eFormZwjjLPREdit: row };
          const layout = { id: 'pZwjjLPRSet' };
          const modal = {
            title: '编辑',
            width: '50vw',
            // height: document.body.clientHeight * 0.55,
            minHeight: document.body.clientHeight * 0.55,
            defaultFullscreen: false,
            destroyOnClose: true,
            open: true,
            showOkBtn: true,
            showCancelBtn: true,
          };
          const inner = {
            onOk: async (_, { origin }, { dc: { close, http, notification }, xe: { get } }) => {
              const inputDate = get(origin, `eFormZwjjLPREdit.inputDate`);
              const year = Number(get(origin, `eFormZwjjLPREdit.year`));
              const month = Number(get(origin, `eFormZwjjLPREdit.month`));
              const id = Number(get(origin, `eFormZwjjLPREdit.id`));
              const params = { inputDate, year, month, id };
              const list = get(origin, 'eGridZwjjLPREdit', []);
              params['list'] = list.map((it) => Object.assign({}, it, { id }));
              await http.post({ url: '/lpzw/cas/saveRate', data: params });
              notification.success({ message: '定价基准利率保存成功', duration: 3 });
              close(true);
            },
          };
          console.log('inner click: ', { inner, layout, modal, transfer });
          open({ inner, layout, modal, transfer });
        },
      },
    },
  },
  {
    name: 'del',
    label: '删除',
    tag: 'row',
    ui: {
      props: {
        icon: 'bi:trash3',
        popConfirm: {
          title: '是否确认删除',
          confirm: async (_0, { row }, _2, { dc: { http, reload } }) => {
            await http.form({ url: '/lpzw/czDebt/deleteDebt', data: { GUIDS: row.GUID } });
            reload();
          },
        },
      },
    },
  },
];
const zwjjLPREditFields: Recordable[] = [
  {
    field: 'id',
    title: '',
    component: 'Input',
    visible: false,
  },
  {
    field: 'inputDate',
    title: '录入日期',
    component: 'DatePicker',
    ui: {
      props: { valueFormat: 'YYYY-MM-DD' },
    },
  },
  {
    field: 'year',
    title: '年份',
    component: 'Input',
    disable: true,
  },
  {
    field: 'month',
    title: '月份',
    component: 'Input',
    disable: true,
  },
];
const zwjjLPREditHead: Recordable[] = [
  {
    field: 'rateTypeName',
    title: '定价基准利率',
    component: 'Input',
    disable: true,
    align: 'left',
    ui: { self: { minWidth: 100 } },
  },
  {
    field: 'rateLevelName',
    title: '计息档次',
    component: 'Input',
    disable: true,
    align: 'left',
    ui: { self: { minWidth: 80 } },
  },
  {
    field: 'rate',
    title: '利率/%',
    component: 'InputNumber',
    align: 'right',
    ui: { self: { minWidth: 120 }, props: { keyboard: true, min: 0, step: 0.1 } },
  },
];

//比较选择的时间是否可以上报
function timeIsConform(time1, time2) {
  if (!time1) return true;
  const date1 = dayjs(dayjs(time1).format('YYYYMM'), 'YYYYMM');
  const date2 = dayjs(time2, 'YYYYMM');
  return date2.isAfter(date1);
}

/****** 举借债务数据 结束 *****************/
export const Pages = [
  {
    id: 'pZwjjBase',
    name: '基本情况',
    remark: '基本情况',
    elements: ['eFormZwjjBase', 'eFormZwjjFile', 'eGridZwjjFile'],
    ui: {
      wrap: { class: 'w-full flex flex-col overflow-auto', component: 'Normal' },
      eFormZwjjBase: { wrap: { class: 'flex pt-2 pr-2' } },
      eFormZwjjFile: {
        alias: 'FormZwjjFileBase',
        params: { _grid_ref: 'GridZwjjFileBase', tabType: 'pZwjjBase' },
        wrap: { class: 'pt-2' },
      },
      eGridZwjjFile: {
        alias: 'GridZwjjFileBase',
        wrap: { class: '' },
        params: { tabType: 'pZwjjBase' },
      },
    },
  },
  {
    id: 'pZwjjDiya',
    name: '抵押',
    remark: '抵押',
    elements: ['eGridZwjjDiya'],
    ui: {
      custom: { show: false },
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjDiya' },
      eGridZwjjDiya: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
    },
  },
  {
    id: 'pZwjjZhiya',
    name: '质押',
    remark: '质押',
    elements: ['eGridZwjjZhiya'],
    ui: {
      custom: { show: false },
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjZhiya' },
      eGridZwjjZhiya: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
    },
  },
  {
    id: 'pZwjjDanbao',
    name: '担保',
    remark: '担保',
    elements: ['eGridZwjjDanbao'],
    ui: {
      custom: { show: false },
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjZhiya' },
      eGridZwjjDanbao: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
    },
  },
  {
    id: 'pZwjjInfo',
    name: '举借信息',
    remark: '举借信息',
    elements: ['eGridZwjjInfo', 'eGridZwjjSub'],
    ui: {
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col' },
      eGridZwjjInfo: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
        params: {
          tabType: 'pZwjjInfo',
        },
      },
      eGridZwjjSub: {
        wrap: { class: 'flex-1 no-header-bottom' },
        params: {
          tabType: 'pZwjjInfo',
        },
      },
    },
  },
  {
    id: 'pZwjjBack',
    name: '还款计划',
    remark: '还款计划',
    elements: ['eGridZwjjBackTop'],
    ui: {
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col' },
      eGridZwjjBackTop: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
        params: {
          tabType: 'pZwjjInfo',
        },
      },
    },
  },
  {
    id: 'pZwjjRate',
    name: '应付利息',
    remark: '应付利息',
    elements: ['eGridZwjjRateTop'],
    ui: {
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col' },
      eGridZwjjRateTop: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
        params: {
          tabType: 'pZwjjInfo',
        },
      },
    },
  },
  {
    id: 'pZwjjCapital',
    name: '偿还本金',
    remark: '偿还本金',
    elements: ['eGridZwjjCapital', 'eFormZwjjFile', 'eGridZwjjFile'],
    ui: {
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjCapital' },
      eGridZwjjCapital: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
      eFormZwjjFile: {
        alias: 'FormZwjjFileCapital',
        params: { _grid_ref: 'GridZwjjFileCapital', tabType: 'pZwjjCapital' },
        wrap: { class: 'flex-0 pt-2' },
      },
      eGridZwjjFile: {
        alias: 'GridZwjjFileCapital',
        params: { CTYPE: 6, tabType: 'pZwjjCapital' },
        wrap: { class: 'flex-0' },
      },
    },
  },
  {
    id: 'pZwjjInterest',
    name: '支付利息罚息',
    remark: '支付利息罚息',
    elements: ['eGridZwjjInterest', 'eFormZwjjFile', 'eGridZwjjFile'],
    ui: {
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjInterest' },
      eGridZwjjInterest: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
      eFormZwjjFile: {
        alias: 'FormZwjjFileInterest',
        params: { _grid_ref: 'GridZwjjFileInterest', tabType: 'pZwjjInterest' },
        wrap: { class: 'flex-0 pt-2' },
      },
      eGridZwjjFile: {
        alias: 'GridZwjjFileInterest',
        params: { CTYPE: 7, tabType: 'pZwjjInterest' },
        wrap: { class: 'flex-0' },
      },
    },
  },
  {
    id: 'pZwjjInvestor',
    name: '实际投资者',
    remark: '实际投资者',
    elements: ['eGridZwjjInvestor'],
    ui: {
      custom: { show: false },
      wrap: { component: 'Normal', class: 'flex-1 flex flex-col pZwjjInvestor' },
      eGridZwjjInvestor: {
        wrap: { class: 'flex-1 relative' },
        self: { class: 'absolute full no-border-top' },
      },
    },
  },
  {
    id: 'pZwjj',
    name: '举借债务',
    remark: '举借债务',
    elements: ['eFormZwjj', 'eGridZwjj', 'eFormDefMoneyUnit'],
    ui: {
      wrap: { component: 'Normal', class: 'w-full m-2 overflow-hidden flex flex-col bg-white p-2' },
      eFormZwjj: {
        wrap: { class: 'flex-0 eFormZwjj' },
        custom: { isSearch: true },
      },
      eGridZwjj: {
        wrap: { class: 'w-full flex-1 relative' },
        self: { class: 'absolute full' },
      },
    },
  },
  {
    id: 'pZwjjM',
    name: '举借债务编辑弹窗',
    remark: '举借债务编辑弹窗',
    buttons: [conststagBtn('pZwjjM')],
    children: [
      'pZwjjBase',
      'pZwjjDiya',
      'pZwjjZhiya',
      'pZwjjDanbao',
      'pZwjjInfo',
      // 'pZwjjBack',
      // 'pZwjjRate',
      'pZwjjCapital',
      'pZwjjInterest',
      'pZwjjInvestor',
    ],
    elements: ['eFormDefMoneyUnit'],
    ui: {
      wrap: {
        component: 'Tab',
        class: 'w-full no-header-bottom',
        active: ({ transfer: { activeKey } }) => activeKey || 'pZwjjBase',
        onChange: async (tab, old, { transfer: { isReadonly } }, { dc: { validate, message } }) => {
          if (isReadonly) return true;
          if (old == 'pZwjjBase') {
            const ret = await validate();
            for (const prop in ret) {
              const item = ret[prop];
              if (item != true) {
                message.warn('请先完善基本信息!');
                return false;
              }
            }
          }
          return true;
        },
      },
    },
  },
  {
    id: 'pZwjjInfoM',
    name: '举借弹窗',
    remark: '新增举借信息弹窗',
    elements: ['eFormDefMoneyUnit', 'eFormZwjjInfo', 'eFormZwjjDrawalMoney', 'eGridZwjjWrap'],
    ui: {
      wrap: { component: 'Normal', class: ['w-full flex flex-col'] },
      eFormZwjjInfo: {
        wrap: {
          class: 'flex-0 b-1 b-solid b-gray px-2',
          style: 'border-color: gray',
          component: 'Legend',
        },
      },
      eFormZwjjDrawalMoney: {
        wrap: {
          class: 'flex-0 b-1 b-solid b-gray px-2',
          style: 'border-color: gray',
          component: 'Legend',
        },
      },
      eGridZwjjWrap: { wrap: { class: 'flex-1 no-header-bottom' } },
    },
  },
  {
    id: 'pZwjjLPRList',
    name: '定价基准利率设置',
    remark: '定价基准利率设置',
    elements: ['eFormZwjjLPRSet', 'eGridZwjjLPRSet'],
    ui: {
      wrap: { component: 'Normal', class: 'w-full m-2 overflow-hidden flex flex-col bg-white p-2' },
      eFormZwjjLPRSet: { wrap: { class: 'flex-0' }, custom: { isSearch: true } },
      eGridZwjjLPRSet: {
        wrap: { class: 'w-full flex-1 relative' },
        self: { class: 'absolute full' },
      },
    },
  },
  {
    id: 'pZwjjLPRSet',
    name: '定价基准编辑',
    remark: '定价基准编辑',
    elements: ['eFormZwjjLPREdit', 'eGridZwjjLPREdit'],
    ui: {
      wrap: { component: 'Normal', class: 'w-full m-2 overflow-hidden flex flex-col bg-white p-2' },
      eFormZwjjLPREdit: { wrap: { class: 'flex-0' } },
      eGridZwjjLPREdit: {
        wrap: { class: 'w-full flex-1 relative' },
        self: { class: 'absolute full' },
      },
    },
  },
];
export const Elements = [
  /** 举借债务 开始 */
  {
    id: 'eFormZwjj',
    component: 'Form',
    fields: zwjjSearchFields,
    ui: {
      props: { showAdvancedButton: zwjjSearchFields.length > 6 },
    },
  },
  {
    id: 'eGridZwjj',
    component: 'Grid',
    fields: zwjjTableFields,
    buttons: zwjjTableButtons,
    ui: {
      props: {
        editConfig: { enabled: false },
        showFooter: true,
      },
      custom: {
        init: async ({ transfer }, { $grid }) => {
          const isBg = transfer.bgAdmin;

          const findOper = $grid.columns.find((i) => i.title === '操作');
          findOper.width = isBg ? 220 : 220;
          $grid.loadColumn($grid.columns);
        },
        load: async (
          data,
          { memory, me, transfer },
          { dc: { http, store }, xe: { set }, dayjs },
        ) => {
          const { items, total, sum } = await http.form({
            url: '/lpzw/czDebt/listDebt',
            data: {
              ...data,
              restMoneyNullFlag: data.restMoneyNullFlag ? '1' : '0',
              sortField: 'GUID',
              sortOrder: 'DESC',
              page: data.page - 1,
              YEAR: dayjs(store.get('user', 'date')).format('YYYY'),
              changeType: transfer.tabType,
            },
          });
          set(memory, `${me}.sum`, sum);
          return {
            items,
            total,
          };
        },
      },
      events: {
        footerMethod: ({ columns }, { me, memory, origin }, { xe }) => {
          const { get, pluck, commafy, toNumber } = xe;
          const ret = [] as Array<any>;
          const sumField = pluck(
            columns.filter(({ params }) => params && params.summary == 'sum'),
            'field',
          );
          const sumData = get(memory, `${me}.sum`, {});
          if (sumField.length) {
            const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
            ret.push(
              columns.map((column, columnIndex) => {
                if (columnIndex === 0) return '合计';
                if (sumField.indexOf(column.field) < 0) return '';
                const cellValue = sumData[column.field];
                return cellValue === undefined
                  ? ''
                  : commafy(toNumber(cellValue / unit), { digits: 6 }).replace(
                      /(?:\.0*|(\.\d+?)0+)$/,
                      '$1',
                    );
              }),
            );
          }
          return ret;
        },
      },
    },
  },
  /** 举借债务 结束 */
  /** 举借基本情况 开始 */
  {
    id: 'eFormZwjjBase',
    component: 'Form',
    fields: zwjjBaseFields,
    ui: {
      custom: {
        disable: ({ field }, { me, def, origin, transfer }, { xe }) => {
          const activeKey = transfer?.tabType;
          if (activeKey && activeKey !== me) return true;
          const check = {
            ITEMNAME: () => xe.get(origin, `${me}.DEBTTYPE`) == '13',
          };
          if (field in check) return check[field]();
          return def;
        },
        visible: ({ field }, { me, def, origin }, { xe }) => {
          const check = {
            PLEDGE_ENTERPRISE: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            FLOAT_LEVEL: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            RATE_FLOAT_CYCLE: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            PLEDGE_DATE: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            FLOATMODE: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            PLEDGE_MONEY: () => xe.get(origin, `${me}.RATETYPE`) == 2,
            FIXEDRATE: () => xe.get(origin, `${me}.RATETYPE`) != 2,
          };
          if (field in check) return check[field]();
          return def;
        },
        required: ({ field }, { def, origin }, { xe }) => {
          const check = {
            ITEMNAME: () => xe.get(origin, 'eFormZwjjBase.DEBTTYPE') != '13',
          };
          if (field in check) return check[field]();
          return def;
        },
        change: async ({ change, origin }, { xe: { get, sum, pluck }, dc: { update } }) => {
          const { path } = change;
          if (path.startsWith('eGridZwjjInfo')) {
            const gridData = get(origin, 'eGridZwjjInfo', []);
            const BMONEY = sum(pluck(gridData, 'MONEY1'));
            const PMONEY = get(origin, 'eFormZwjjBase.AGREEMONEY') - BMONEY;
            update({ path: 'eFormZwjjBase', value: { BMONEY, PMONEY } });
          }
        },
        init: async (
          { transfer: { eFormZwjjBase: data }, memory, me },
          { dc: { update }, xe: { set, clone } },
        ) => {
          const value = data ?? {};
          set(memory, me, clone(value, true));
          await update({ path: 'eFormZwjjBase', value });
        },
      },
      props: {
        labelWidth: 200,
        baseColProps: { span: 8 },
        showAdvancedButton: false, // 防止超出行数自动隐藏
        showActionButtonGroup: false,
        submitOnReset: false,
      },
    },
  },
  /** 举借基本情况 结束 */
  /** 抵押 开始 */
  {
    id: 'eGridZwjjDiya',
    component: 'Grid',
    fields: zwjjDiyaTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dayjs, dc, xe }) => {
          const { http, store, update } = dc;
          const { isReadonly, GUID, eGridZwjjDiya } = transfer;
          const { clone, set, toArrayTree } = xe;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = GUID
            ? await http.form({
                url: '/lpzw/czDebt/listDebtSub',
                data: { DEBTGUID: GUID, YEAR: year, CTYPE: 1 },
              })
            : { items: eGridZwjjDiya || [] };
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 22 },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str2TypeColumn = $grid.getColumnByField('STR2');
          set(str2TypeColumn, 'params.options', _treeData);
          const _tmp3: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 53 },
          });
          const _treeData3 = toArrayTree(_tmp3, { parentKey: 'pid' });
          const str3TypeColumn = $grid.getColumnByField('STR3');
          set(str3TypeColumn, 'params.options', _treeData3);
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  /** 抵押 结束 */
  /** 质押 开始 */
  {
    id: 'eGridZwjjZhiya',
    component: 'Grid',
    fields: zwjjZhiyaTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dayjs, dc, xe }) => {
          const { http, store, update } = dc;
          const { isReadonly, GUID, eGridZwjjZhiya } = transfer;
          const { clone, set, toArrayTree } = xe;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = GUID
            ? await http.form({
                url: '/lpzw/czDebt/listDebtSub',
                data: { DEBTGUID: GUID, YEAR: year, CTYPE: 14 },
              })
            : { items: eGridZwjjZhiya || [] };
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { OPERATORGUID: 1, type: -1, YEAR: year, depart: '793.' },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str4TypeColumn = $grid.getColumnByField('STR4');
          set(str4TypeColumn, 'params.options', _treeData);
          const _tmp2: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 54 },
          });
          const _treeData2 = toArrayTree(_tmp2, { parentKey: 'pid' });
          const str3TypeColumn = $grid.getColumnByField('STR3');
          set(str3TypeColumn, 'params.options', _treeData2);
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  /** 质押 结束 */
  /** 担保 开始 */
  {
    id: 'eGridZwjjDanbao',
    component: 'Grid',
    fields: zwjjDanbaoTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dayjs, dc, xe }) => {
          const { http, store, update } = dc;
          const { isReadonly, GUID, eGridZwjjDanbao } = transfer;
          const { clone, set, toArrayTree } = xe;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = GUID
            ? await http.form({
                url: '/lpzw/czDebt/listDebtSub',
                data: { DEBTGUID: GUID, YEAR: year, CTYPE: 2 },
              })
            : { items: eGridZwjjDanbao || [{}] };
          set(memory, me, clone(value, true));
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { OPERATORGUID: 1, type: -1, YEAR: year, depart: '793.' },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str1TypeColumn = $grid.getColumnByField('STR1');
          const str4TypeColumn = $grid.getColumnByField('STR4');
          set(str1TypeColumn, 'params.options', _treeData);
          set(str4TypeColumn, 'params.options', _treeData);
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  /** 担保 结束 */
  /** 举借信息 开始 */
  {
    id: 'eGridZwjjInfo',
    component: 'Grid',
    fields: zwjjInfoTableFields,
    buttons: zwjjEditButtons,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dc, xe }) => {
          const { http, update } = dc;
          const isReadonly = getIsReadonlyByActiveKey(transfer, 'pZwjjInfo');
          const { clone, set, toArrayTree, uniqueId } = xe;
          const value = transfer[me] ?? [];
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 32 },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str1TypeColumn = $grid.getColumnByField('STR1');
          set(str1TypeColumn, 'params.options', _treeData);
          if (!isReadonly && !value.length) value.push({ _id: uniqueId() });
          set(memory, me, clone(value, true));
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      events: {
        onCurrentChange: ({ row, $event }, { me }, { dc: { send } }) => {
          console.log('grid current change: ', $event, row);
          $event.isCurrentChange = true;
          send({ path: me, action: 'active', value: row });
        },
        onCellClick: ({ $grid, $event }, { me }, { dc: { send } }) => {
          if (!$event.isCurrentChange) {
            $grid.clearCurrentRow();
            send({ path: me, value: {}, action: 'clear' });
          }
          console.log('grid click: ', $event, $grid, send);
        },
        onCellDblclick: async ({ row }, { origin, transfer: transferM }, { xe, dc }) => {
          const isReadonly = getIsReadonlyByActiveKey(transferM, 'pZwjjInfo');
          if (!isReadonly) return;
          const { get } = xe;
          const { open } = dc;
          const base = { ...get(origin, 'eFormZwjjBase'), ...row };
          const eGridZwjjBackEdit = get(origin, 'eGridZwjjBack', []).filter(
            ({ AMOUNT }) => [row.GUID, row._id].indexOf(AMOUNT) > -1,
          );
          const eFormZwjjDrawalMoney = Object.assign({}, base, row);
          const transfer = { eFormZwjjInfo: base, eFormZwjjDrawalMoney, eGridZwjjBackEdit };
          const inner = {};
          const layout = { id: 'pZwjjInfoM' };
          const modal = {
            title: '举借信息(单位：万元)',
            width: '70vw',
            height: 700,
            minHeight: 700,
            defaultFullscreen: false,
            destroyOnClose: true,
            centered: true,
            open: true,
            showOkBtn: false,
            showCancelBtn: false,
          };
          console.log('inner click: ', { inner, layout, modal, transfer });
          open({ inner, layout, modal, transfer: { ...transfer, isReadonly } });
        },
      },
      props: {
        editConfig: { enabled: false },
        keyboardConfig: {
          isArrow: true,
          isEsc: true,
          isDel: true,
          isEnter: true,
          isTab: true,
          isEdit: true,
          enterToTab: true,
        },
        proxyConfig: { enabled: false },
        rowConfig: { isCurrent: true },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  {
    id: 'eGridZwjjSub',
    name: '举借子表',
    children: ['eGridZwjjBack', 'eGridZwjjRate'],
    ui: {
      eGridZwjjBack: {
        wrap: { class: 'h-full relative' },
        self: { class: 'absolute full no-border-top' },
      },
      eGridZwjjRate: {
        wrap: { class: 'h-full relative' },
        self: { class: 'absolute full no-border-top' },
      },
    },
  },
  /** 举借信息 结束 */
  /** 还款计划 开始 */
  {
    id: 'eGridZwjjBack',
    name: '还款计划',
    component: 'Grid',
    fields: zwjjBackTableFields,
    ui: {
      custom: {
        recv: async ({ msg: { path, value, action } }, { $grid }) => {
          if (path.indexOf('eGridZwjjInfo') > -1) {
            console.log('msg change: ', $grid);
            if (['clear', 'active'].indexOf(action) > -1) {
              if (action == 'clear') {
                await $grid.clearFilter('AMOUNT');
              } else {
                await $grid.setFilter('AMOUNT', [{ data: value._id ?? value.GUID, checked: true }]);
              }
              await $grid.updateData();
            }
          }
        },
        init: async ({ me, transfer }, { $grid, dc: { http, update }, xe: { set, uniq } }) => {
          const ret: any = await http.form({ url: '/lpzw/cas/selectRate' });
          const str2TypeColumn = $grid.getColumnByField('STR2');
          set(str2TypeColumn, 'params.options', ret);
          const value = transfer[me] ?? [];
          value.forEach((it) => {
            if ('STR2' in it && `${it.STR2}` !== '') it.STR2 = parseInt(it.STR2);
            if ('STR3' in it && `${it.STR3}` !== '') it.STR3 = parseInt(it.STR3);
          });
          const str3TypeColumn = $grid.getColumnByField('STR3');
          for (const str2 of uniq(value.map(({ STR2 }) => STR2).filter((it) => !!it))) {
            const ret: any = await http.form({ url: '/lpzw/cas/getRateSub', data: { id: str2 } });
            set(str3TypeColumn, `params.options.${str2}`, ret);
          }
          update({ path: me, action: 'load', value });
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  {
    id: 'eGridZwjjBackTop',
    name: '还款计划',
    component: 'Grid',
    fields: zwjjBackTableFields,
    ui: {
      custom: {
        init: async ({ me, transfer }, { dayjs, dc: { http, store, update } }) => {
          const { GUID } = transfer;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = await http.form({
            url: '/lpzw/czDebt/listDebtSub',
            data: { DEBTGUID: GUID, YEAR: year, CTYPE: 4 },
          });
          await update({ path: me, action: 'load', value: value });
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  //举借信息编辑中的还款计划
  {
    id: 'eGridZwjjBackEdit',
    name: '还款计划',
    component: 'Grid',
    fields: zwjjBackTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async (
          { me, memory, transfer },
          { $grid, dc: { http, next, update }, xe: { clone, set, uniq } },
        ) => {
          const ret: any = await http.form({ url: '/lpzw/cas/selectRate' });
          const str2TypeColumn = $grid.getColumnByField('STR2');
          set(str2TypeColumn, 'params.options', ret);
          const value = transfer[me] ?? [];
          value.forEach((it) => {
            if ('STR2' in it && `${it.STR2}` !== '') it.STR2 = parseInt(it.STR2);
            if ('STR3' in it && `${it.STR3}` !== '') it.STR3 = parseInt(it.STR3);
          });
          const str3TypeColumn = $grid.getColumnByField('STR3');
          for (const str2 of uniq(value.map(({ STR2 }) => STR2).filter((it) => !!it))) {
            const ret: any = await http.form({ url: '/lpzw/cas/getRateSub', data: { id: str2 } });
            set(str3TypeColumn, `params.options.${str2}`, ret);
          }
          const { isReadonly } = transfer;
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await next();
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: true },
        toolbarConfig: { enabled: false },
        showFooter: true,
        proxyConfig: { enabled: false },
        editRules: {
          DATE1: [
            {
              required: true,
            },
          ],
          MONEY1: [
            {
              required: true,
            },
          ],
        },
      },
    },
  },
  /** 还款计划 结束 */
  /** 应付利息 开始 */
  {
    id: 'eGridZwjjRate',
    name: '应付利息',
    component: 'Grid',
    fields: zwjjRateTableFields,
    ui: {
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
      custom: {
        recv: async ({ msg: { path, value, action } }, { $grid }) => {
          if (path.indexOf('eGridZwjjInfo') > -1) {
            console.log('msg change: ', $grid);
            if (['clear', 'active'].indexOf(action) > -1) {
              if (action == 'clear') {
                await $grid.clearFilter('AMOUNT');
              } else {
                await $grid.setFilter('AMOUNT', [{ data: value._id ?? value.GUID, checked: true }]);
              }
              await $grid.updateData();
            }
          }
        },
        init: async ({ me, origin, transfer }, { dc: { update }, xe: { get } }) => {
          const value = transfer[me] ?? [];
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          value.map((it) => {
            const _arr = it.AMOUNTTEXT.split('|');
            _arr[1] /= unit;
            it.AMOUNTTEXT = _arr.join('|');
          });
          await update({ path: me, action: 'load', value: value });
        },
      },
    },
  },
  {
    id: 'eGridZwjjRateTop',
    name: '应付利息',
    component: 'Grid',
    fields: zwjjRateTableFields,
    ui: {
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
      custom: {
        init: async (
          { me, origin, transfer },
          { dayjs, dc: { http, store, update }, xe: { get } },
        ) => {
          const { GUID } = transfer;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = await http.form({
            url: '/lpzw/czDebt/listDebtSub',
            data: { DEBTGUID: GUID, YEAR: year, CTYPE: 5 },
          });
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          value.map((it) => {
            const _arr = it.AMOUNTTEXT.split('|');
            _arr[1] /= unit;
            it.AMOUNTTEXT = _arr.join('|');
            return it;
          });
          await update({ path: me, action: 'load', value: value });
        },
      },
    },
  },
  {
    id: 'eGridZwjjRateEdit',
    name: '应付利息',
    component: 'Grid',
    fields: zwjjRateEditFields,
    ui: {
      props: {
        editConfig: { enabled: true },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: {
          enabled: true,
          refresh: false,
          zoom: false,
          custom: false,
          tools: [{ name: '生成利息', code: 'gen', circle: false }],
        },
      },
      events: {
        onToolbarToolClick: async ({ code, ...args }, data, lib) => {
          if (code != 'gen') return;
          console.log('gen: ', args, data, lib);
          // 生成利息
          const dayjs = lib.dayjs;
          const { Confirm, Warn, http, update } = lib.dc;
          const { get } = lib.xe;
          const {
            origin,
            me,
            transfer: { eGridZwjjCapital },
          } = data;
          const MONEY2 = get(origin, 'eFormZwjjDrawalMoney.MONEY2', 0); // 提款金额
          if (MONEY2 <= 0) return Warn({ title: '提款金额必须大于0!' });
          const DATE1 = get(origin, 'eFormZwjjDrawalMoney.DATE1', null); // 提款日期
          if (DATE1 == null) return Warn({ title: '提款日期不能为空!' });
          const DATE2 = get(origin, 'eFormZwjjDrawalMoney.DATE2', null); // 截止日期
          if (DATE2 == null) return Warn({ title: '截止日期不能为空!' });
          const STR4 = get(origin, 'eFormZwjjDrawalMoney.STR4', 0); // 付息方式
          if (STR4 <= 0) return Warn({ title: '请选择付息方式!' });
          const ret = await new Promise((resolve) => {
            Confirm({
              iconType: 'warning',
              title: '清空并重新生成利息?',
              onOk: async () => resolve(true),
              onCancel: async () => resolve(false),
            });
          });
          if (!ret) return;
          const sjhk = eGridZwjjCapital.filter(({ MONEY2 = 0 }) => MONEY2 > 0);
          const hkjh = get(origin, 'eGridZwjjBackEdit', []).filter(
            ({ MONEY1 = 0, DATE1 = '' }) => MONEY1 > 0 && DATE1 != '',
          );
          // .sort(({ DATE1: l }, { DATE1: r }) => (l > r ? 1 : -1)); // 还款计划
          const qxrq = dayjs(DATE1).add(1, 'day').format('YYYY-MM-DD'); // 起息日期
          const zje = get(origin, 'eFormZwjjDrawalMoney.MONEY1', 0); // 举借总额
          const hkxx: Recordable[] = [];
          for (let i = 0; i < hkjh.length; ++i) {
            let hkrq = null,
              hkje = 0,
              STR2 = null,
              STR3 = null;
            for (let j = 0; j < sjhk.length; ++j) {
              if (sjhk[j].AMOUNT == hkjh[i].GUID) {
                (hkrq = sjhk[j].DATE1), (hkje = sjhk[j].MONEY1);
                (STR2 = hkjh[i].STR2), (STR3 = hkjh[i].STR3);
                break;
              }
            }
            if (!hkje) {
              (hkrq = hkjh[i].DATE1), (hkje = hkjh[i].MONEY1);
              (STR2 = hkjh[i].STR2), (STR3 = hkjh[i].STR3);
            }
            hkxx.push({ hkrq, hkje, STR2, STR3 });
          }

          const getFxxx = function (start, end, fxfs) {
            const jdfxrq = [end];
            if (fxfs == '3') {
              //按季度还款
              const m = ['03-21', '06-21', '09-21', '12-21'];
              const startYear = start.substring(0, 4);
              const endYear = end.substring(0, 4);

              for (let i = 0; i < m.length; i++) {
                for (let j = startYear; j <= endYear; j++) {
                  const day = j + '-' + m[i];
                  if (start < day && end > day) {
                    jdfxrq.push(day);
                  }
                }
              }
              return jdfxrq.sort();
            }

            for (let i = 1; ; ++i) {
              const fxrq = dayjs(start)
                .add(fxfs * i, 'month')
                .format('YYYY-MM-DD');
              if (fxrq > end) break;
              jdfxrq.push(fxrq);
            }
            return jdfxrq.sort();
          };
          const getFloatRate = function (rate) {
            const STR8 = get(origin, 'eFormZwjjDrawalMoney.STR8'); // 利率浮动方式
            const RATE4 = get(origin, 'eFormZwjjDrawalMoney.RATE4'); // 加减点数

            if (STR8 == 1) return rate * (1 + RATE4);
            if (STR8 == 2) return rate * (1 - RATE4);
            if (STR8 == 3) return rate + RATE4 / 100;
            if (STR8 == 4) return rate - RATE4 / 100;

            return rate;
          };
          const fxxx = getFxxx(qxrq, hkxx[hkxx.length - 1].hkrq, STR4);
          const fdllxx: Recordable[] = [
            { tzsj: '2022-03-16', ll: '0.01' },
            { tzsj: '2022-05-16', ll: '0.02' },
          ]; // 浮动利率
          const lvlx = get(origin, 'eFormZwjjDrawalMoney.STR5'); // 利率类型
          const gdll = `${lvlx}` === '1'; // 是否固定利率 1是 0否
          const gdllxx = gdll ? get(origin, 'eFormZwjjDrawalMoney.RATE2') : 0.03; //固定利率
          if (`${lvlx}` === '2') {
            const rateLevel = get(origin, 'eFormZwjjDrawalMoney.STR7');
            const _tmp = await http.form({ url: '/lpzw/cas/getRateDetail', data: { rateLevel } });
            fdllxx.splice(0, fdllxx.length, ..._tmp);
            fdllxx.map((it) => (it.ll = getFloatRate(it.ll)));
          }
          console.log(`qxrq(${qxrq}), zje(${zje})`, hkjh, sjhk, hkxx, fxxx, fdllxx);
          const fxmx: Recordable[] = []; // 付息明细
          let count = 0; // 计数还款
          let bj = zje; // 本金
          let startDate = qxrq;
          for (let i = 0; i < fxxx.length; ++i) {
            for (let j = count; j < hkxx.length; ++j) {
              if (fxxx[i] >= hkxx[j].hkrq) {
                const endDate = hkxx[j].hkrq;
                if (gdll) {
                  // 固定利率
                  const dd = dayjs(endDate).diff(startDate, 'day') + 1;
                  const lxje = (bj * dd * gdllxx) / 360 / 100;
                  fxmx.push({ startDate, endDate, lxje, bj, ll: gdllxx, fxrq: fxxx[i] });
                  startDate = dayjs(hkxx[j].hkrq).add(1, 'day').format('YYYY-MM-DD');
                } else {
                  if (hkxx[j].STR2 && hkxx[j].STR3) {
                    // 该期次还款指定利率
                    const rateLevel = hkxx[j].STR3;
                    const rateDetail = await http.form({
                      url: '/lpzw/cas/getRateRetailByIdAndRateLevel',
                      data: { id: hkxx[j].STR2, rateLevel },
                    });
                    const rate = getFloatRate(rateDetail[0].RATE);
                    const dd = dayjs(endDate).diff(startDate, 'day') + 1;
                    const lxje = (((bj * dd) / 360) * rate) / 100;
                    fxmx.push({ startDate, endDate, lxje, bj, ll: rate, fxrq: fxxx[i] });
                    startDate = dayjs(endDate).add(1, 'day').format('YYYY-MM-DD');
                  } else {
                    // 浮动利率
                    for (let k = 0; k < fdllxx.length; ++k) {
                      const ll = fdllxx[k].ll;
                      if (k == fdllxx.length - 1 || endDate < fdllxx[k + 1].tzsj) {
                        // 日期比调整日期小或者最后一条直接结束
                        const dd = dayjs(hkxx[j].hkrq).diff(startDate, 'day') + 1;
                        const lxje = (((bj * dd) / 360) * ll) / 100;
                        fxmx.push({ startDate, endDate, lxje, bj, ll, fxrq: fxxx[i] });
                        startDate = dayjs(endDate).add(1, 'day').format('YYYY-MM-DD');
                        break;
                      }
                      const tzsj = fdllxx[k + 1].tzsj;
                      if (endDate >= tzsj && startDate < tzsj) {
                        // 跨越下一个利息调整日期
                        const dd = dayjs(tzsj).diff(startDate, 'day') + 1;
                        const lxje = (((bj * dd) / 360) * ll) / 100;
                        fxmx.push({ startDate, endDate, lxje, bj, ll, fxrq: fxxx[i] });
                        startDate = tzsj;
                      }
                    }
                  }
                }
                count = j + 1; // 计算还款的位置
                bj -= hkxx[j].hkje;
              }
            }
            if (gdll) {
              if (bj > 0) {
                const dd = dayjs(fxxx[i]).diff(startDate, 'day') + 1;
                const lxje = (bj * dd * gdllxx) / 360 / 100;
                fxmx.push({ startDate, endDate: fxxx[i], lxje, bj, ll: gdllxx, fxrq: fxxx[i] });
              }
            } else {
              if (bj > 0) {
                // 检查是否指定利率 找比它大的一个还款信息里有没有选择利率
                let isHavRate = false;
                const endDate = fxxx[i];
                for (let j = 0; j < hkxx.length; ++j) {
                  if (hkxx[j].hkrq >= endDate) {
                    if (hkxx[j].STR2 && hkxx[j].STR3) {
                      const rateLevel = hkxx[j].STR3;
                      const rateDetail = await http.form({
                        url: '/lpzw/cas/getRateRetailByIdAndRateLevel',
                        data: { id: hkxx[j].STR2, rateLevel },
                      });
                      const rate = getFloatRate(rateDetail[0].RATE);
                      const dd = dayjs(endDate).diff(startDate, 'day') + 1;
                      const lxje = (((bj * dd) / 360) * rate) / 100;
                      fxmx.push({ startDate, endDate, lxje, bj, ll: rate, fxrq: endDate });
                      startDate = dayjs(endDate).add(1, 'day').format('YYYY-MM-DD');
                      isHavRate = true;
                    }
                  }
                }
                if (!isHavRate) {
                  for (let k = 0; k < fdllxx.length; ++k) {
                    const ll = fdllxx[k].ll;
                    if (k == fdllxx.length - 1 || endDate < fdllxx[k + 1].tzsj) {
                      const dd = dayjs(endDate).diff(startDate, 'day') + 1;
                      // 日期比调整日期小或者最后一条直接结束
                      const lxje = (((bj * dd) / 360) * ll) / 100;
                      fxmx.push({ startDate, endDate, lxje, bj, ll, fxrq: endDate });
                      startDate = dayjs(endDate).add(1, 'day').format('YYYY-MM-DD');
                      break;
                    }
                    const { tzsj } = fdllxx[k + 1];
                    if (endDate >= tzsj && startDate < tzsj) {
                      const dd = dayjs(tzsj).diff(startDate, 'day') + 1;
                      // 跨越下一个利息调整日期  把当前利息结算掉
                      const lxje = (((bj * dd) / 360) * ll) / 100;
                      const end = dayjs(tzsj).subtract(1, 'day');
                      fxmx.push({ startDate, endDate: end, lxje, bj, ll, fxrq: endDate });
                      startDate = tzsj;
                    }
                  }
                }
              }
            }
            startDate = dayjs(fxxx[i]).add(1, 'day').format('YYYY-MM-DD');
          }
          const fxhz: Recordable[] = [];
          for (let i = 0; i < fxmx.length; ++i) {
            fxmx[i].qsrq = fxmx[i].startDate;
            fxmx[i].jzrq = fxmx[i].endDate;
            fxmx[i].lxje = parseFloat(fxmx[i].lxje).toFixed(6);

            let isOver = false;
            for (let j = 0; j < fxhz.length; ++j) {
              if (fxhz[j].DATE1 == fxmx[i].fxrq) {
                fxhz[j].MONEY1 += parseFloat(fxmx[i].lxje);
                isOver = true;
                break;
              }
            }
            if (isOver) continue;
            fxhz.push({ DATE1: fxmx[i].fxrq, MONEY1: parseFloat(fxmx[i].lxje) });
          }
          // fxhz.map((it) => (it.MONEY1 = commafy(toNumber(it.MONEY1), { digits: 2 })));
          await update({ path: me, action: 'load', value: fxhz });
        },
      },
      custom: {
        init: async ({ me, transfer }, { instance, dc: { update }, xe: { set } }) => {
          const { isReadonly } = transfer;
          const value = transfer[me] ?? [];
          if (!isReadonly && !value.length) value.push({});
          const openEdit = { editConfig: { enabled: !isReadonly }, toolbarConfig: { tools: [{}] } };
          const wrapNode = instance.proxy.$el.parentNode;
          console.log('instance: ', wrapNode);
          wrapNode.classList[isReadonly ? 'remove' : 'add']('dmt');
          set(openEdit, 'toolbarConfig.enabled', !isReadonly);
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value: value });
        },
      },
    },
  },
  /** 应付利息 结束 */
  /** 偿还本金 开始 */
  {
    id: 'eGridZwjjCapital',
    component: 'Grid',
    fields: zwjjCapitalTableFields,
    buttons: bGridCapitalTableEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, origin, transfer }, { $grid, dayjs, dc, xe }) => {
          const { http, store, update } = dc;
          const { GUID, eGridZwjjCapital } = transfer;
          const isReadonly = getIsReadonlyByActiveKey(transfer, 'pZwjjCapital');
          const { clone, get, set, toArrayTree } = xe;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 32 },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str1TypeColumn = $grid.getColumnByField('STR1');
          set(str1TypeColumn, 'params.options', _treeData);

          const zwjjInfo = get(transfer, 'eGridZwjjInfo', []);
          const zwjjBack = clone(get(transfer, 'eGridZwjjBack', []), true);
          const unit = get(origin, 'eFormDefMoneyUnit._.unit', 1);
          const ret = zwjjBack
            .filter(({ GUID }) => GUID)
            .map((it) => {
              const zwjj = zwjjInfo.find(({ GUID }) => GUID == it.AMOUNT);
              const text = `${it.DATE1}(${it.MONEY1 / unit})`;
              const money = it.MONEY1 == null ? 0 : parseFloat(it.MONEY1);
              const rate = zwjj.RATE == null ? 0 : parseFloat(zwjj.RATE);
              return {
                id: it.GUID,
                AMOUNTTEXT: text,
                PLANMONEY: zwjj.MONEY1,
                AMOUNT: it.GUID,
                MONEY1: it.MONEY1,
                MONEY2: money * rate,
                DATE1: '',
                STR1: zwjj.STR1,
              };
            });
          const textColumn = $grid.getColumnByField('AMOUNTTEXT');
          set(textColumn, 'params.options', ret);

          const { items: value } = GUID
            ? await http.form({
                url: '/lpzw/czDebt/listDebtSub',
                data: { DEBTGUID: GUID, YEAR: year, CTYPE: 6 },
              })
            : { items: eGridZwjjCapital || [] };
          if (!isReadonly && !value.length) value.push({});
          value.map((it) => {
            if (it.AMOUNTTEXT)
              it.AMOUNTTEXT = it.AMOUNTTEXT.replace(/\((\d+)\)/, (a, _1) => `(${_1 / unit})`);
          });
          console.log('偿还本金: ', value);
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: {
          enabled: false,
          showStatus: false,
          beforeEditMethod({ row }, { transfer }) {
            if (
              transfer.maxReportMonth &&
              row.DATE1 &&
              !timeIsConform(transfer.maxReportMonth, row.DATE1)
            ) {
              return false;
            } else {
              return true;
            }
          },
        },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
        editRules: { AMOUNTTEXT: [{ required: true }] },
      },
    },
  },
  /** 偿还本金 结束 */
  /** 支付利息罚息 开始 */
  {
    id: 'eGridZwjjInterest',
    component: 'Grid',
    fields: zwjjInterestTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dayjs, dc, xe }) => {
          const { http, store, update } = dc;
          const { GUID, eGridZwjjInterest } = transfer;
          const isReadonly = getIsReadonlyByActiveKey(transfer, 'pZwjjInterest');
          const { clone, set, toArrayTree } = xe;
          const year = dayjs(store.get('user', 'date')).format('YYYY');
          const { items: value } = GUID
            ? await http.form({
                url: '/lpzw/czDebt/listDebtSub',
                data: { DEBTGUID: GUID, YEAR: year, CTYPE: 7 },
              })
            : { items: eGridZwjjInterest || [] };
          const _tmp: any = await http.form({
            url: '/lpzw/czItem/listItemCombo',
            data: { type: 3, BMTYPE: 32 },
          });
          const _treeData = toArrayTree(_tmp, { parentKey: 'pid' });
          const str2TypeColumn = $grid.columns.find(({ field }) => field == 'STR2');
          set(str2TypeColumn, 'params.options', _treeData);
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  /** 支付利息罚息 结束 */
  /** 债务信息 开始 */
  {
    id: 'eFormZwjjInfo',
    component: 'Form',
    name: '债务信息',
    fields: zwjjInfoFields,
    ui: {
      custom: {
        init: ({ me, transfer }, { dc: { update } }) => {
          const data = { ...transfer[me] };
          update({ path: 'eFormZwjjInfo', value: data });
        },
      },
      props: {
        labelWidth: 200,
        baseColProps: { span: 8 },
        showAdvancedButton: false,
        showActionButtonGroup: false,
      },
    },
  },
  {
    id: 'eFormZwjjDrawalMoney',
    component: 'Form',
    name: '提款信息',
    fields: zwjjDrawalMoneyFields,
    ui: {
      custom: {
        init: async ({ me, transfer }, { dc: { next, update } }) => {
          const data = transfer[me];
          await next();
          await update({
            path: me,
            value: {
              ...data,
              RATE: undefined,
              STR4: data.STR4 ?? data.INTEREST_WAY, // 付息方式
              RATE3: data.RATE3 ?? data.COMPLEXRATE, // 放款综合利率
              STR5: data.STR5 ?? data.RATETYPE, // 利率类型
              STR6: data.STR6 ?? data.PLEDGE_ENTERPRISE, // 定价基础利率
              RATE4: data.RATE4 ?? data.PLEDGE_MONEY, // 加减点数
              STR7: data.STR7 ?? data.FLOAT_LEVEL, // 计息档次
              STR9: data.STR9 ?? data.RATE_FLOAT_CYCLE, // 计息档次
              RATE2: data.RATE2 ?? data.FIXEDRATE, // 利率(%)
            },
          });
          // TODO  一次更新没有再次触发显示隐藏
          //提款汇率
          update({ path: me, value: { RATE: data.RATE ?? data.EXRATE } });
        },
        required: ({ field }, { me, def, origin }, { xe }) => {
          const check = {
            _gap: () => xe.get(origin, `${me}.STR5`) == 2,
            STR6: () => xe.get(origin, `${me}.STR5`) == 2,
            STR7: () => xe.get(origin, `${me}.STR5`) == 2,
            STR8: () => xe.get(origin, `${me}.STR5`) == 2,
            PLEDGE_DATE: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE_FLOAT_CYCLE: () => xe.get(origin, `${me}.STR5`) == 2,
            DATE5: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE4: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE2: () => xe.get(origin, `${me}.STR5`) != 2,
          };
          if (field in check) return check[field]();
          return def;
        },
        visible: ({ field }, { me, def, origin }, { xe }) => {
          const check = {
            _gap: () => xe.get(origin, `${me}.STR5`) == 2,
            STR6: () => xe.get(origin, `${me}.STR5`) == 2,
            STR7: () => xe.get(origin, `${me}.STR5`) == 2,
            STR8: () => xe.get(origin, `${me}.STR5`) == 2,
            PLEDGE_DATE: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE_FLOAT_CYCLE: () => xe.get(origin, `${me}.STR5`) == 2,
            DATE5: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE4: () => xe.get(origin, `${me}.STR5`) == 2,
            RATE2: () => xe.get(origin, `${me}.STR5`) != 2,
          };
          if (field in check) return check[field]();
          return def;
        },
        change: async ({ change, origin }, { xe: { get }, dc: { update } }) => {
          console.log('inner data change: ', change);
          const { path, value } = change;
          if (path.startsWith('eFormZwjjDrawalMoney.MONEY1')) {
            update({
              path: 'eFormZwjjDrawalMoney',
              value: { MONEY2: get(origin, 'eFormZwjjDrawalMoney.RATE') * value },
            });
          }
        },
      },
      props: {
        labelWidth: 200,
        baseColProps: { span: 8 },
        showAdvancedButton: false,
        showActionButtonGroup: false,
      },
    },
  },
  {
    id: 'eGridZwjjWrap',
    name: '举借数据',
    children: ['eGridZwjjBackEdit', 'eGridZwjjRateEdit'],
    ui: {
      eGridZwjjBackEdit: {
        wrap: { class: 'h-full relative' },
        self: { class: 'absolute full no-border-top' },
      },
      eGridZwjjRateEdit: {
        wrap: {
          class: 'h-full relative pointer-none dmt',
          style: '--dynamic-size: -50px; --component-background-color: transparent; z-index: 1000;',
        },
        self: { class: 'absolute full no-border-top transparent' },
      },
    },
  },
  /** 债务信息 结束 */
  /** 实际投资人 开始 */
  {
    id: 'eGridZwjjInvestor',
    component: 'Grid',
    fields: zwjjInvestorTableFields,
    buttons: bGridCommonEdit,
    ui: {
      custom: {
        change: async ({ origin, change, me }, { xe: { get }, dc: { update } }) => {
          const { action, path } = change;
          if (!path.startsWith(me)) return;
          if (action == 'del' && !get(origin, me).length)
            update({ path: me, action: 'add', value: {} });
        },
        init: async ({ me, memory, transfer }, { $grid, dc: { update }, xe: { clone, set } }) => {
          const { isReadonly } = transfer;
          const value = transfer[me] ?? [];
          if (!isReadonly && !value.length) value.push({});
          set(memory, me, clone(value, true));
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
          await update({ path: me, action: 'load', value });
          await $grid[isReadonly ? 'hideColumn' : 'showColumn']($grid.getColumnById('oper'));
        },
      },
      props: {
        editConfig: { enabled: true },
        proxyConfig: { enabled: false },
        showFooter: true,
        toolbarConfig: { enabled: false },
      },
    },
  },
  ...fileUploadElement('eFormZwjjFile', 'eGridZwjjFile'),
  /** 定价基准利率设置 开始 */
  {
    id: 'eFormZwjjLPRSet',
    component: 'Form',
    fields: zwjjLPRSearchFields,
    buttons: zwjjLPRFormButtons,
    ui: {
      props: {
        showResetButton: false,
        actionColOptions: { style: 'margin-left: unset;' },
      },
    },
  },
  {
    id: 'eGridZwjjLPRSet',
    component: 'Grid',
    fields: zwjjLPRListFields,
    buttons: zwjjLPRFormButtons,
    ui: {
      props: { editConfig: { enabled: false }, toolbarConfig: { enabled: false } },
      custom: {
        load: async (data, _, { dc: { http }, xe: { omit } }) => {
          const params = omit(data, ['date']);
          if (data['date']) {
            const [year, month] = data['date'].split('-');
            Object.assign(params, { year, month });
          }
          return http.post({ url: '/lpzw/cas/pageRate', data: params });
        },
        init: async (_, { $grid }) => $grid.commitProxy('_init'),
      },
    },
  },
  {
    id: 'eFormZwjjLPREdit',
    component: 'Form',
    fields: zwjjLPREditFields,
    ui: {
      custom: {
        init: ({ me, transfer }, { dc: { update } }) => update({ path: me, value: transfer[me] }),
      },
      props: {
        showResetButton: false,
        showSubmitButton: false,
        baseColProps: { span: 8 },
        actionColOptions: { style: 'margin-left: unset;' },
      },
    },
  },
  {
    id: 'eGridZwjjLPREdit',
    component: 'Grid',
    fields: zwjjLPREditHead,
    ui: {
      props: {
        editConfig: { enabled: false },
        proxyConfig: { enabled: false },
        toolbarConfig: { enabled: false },
      },
      custom: {
        // init: async ({ me, transfer }, { $grid, dc: { next, update } }) => {
        init: async ({ me, transfer }, { dc: { http, update }, xe: { get, omit } }) => {
          console.log('init: ', transfer);
          const id = get(transfer, 'eFormZwjjLPREdit.id', '');
          const isReadonly = get(transfer, 'isReadonly', false);
          if (id) {
            const value = await http.post({ url: '/lpzw/cas/listRateSub', data: { id } });
            const val = value.map((it) => omit(it, ['id']));
            await update({ path: me, action: 'load', value: val });
          } else {
            const value = [
              { rateLevel: '11', rateTypeName: 'LPR利率', rateType: '1', rateLevelName: '一年' },
              { rateLevel: '15', rateTypeName: 'LPR利率', rateType: '1', rateLevelName: '五年' },
              {
                rateLevel: '21',
                rateTypeName: '央行基准利率',
                rateType: '2',
                rateLevelName: '一年以内（含一年）',
              },
              {
                rateLevel: '25',
                rateTypeName: '央行基准利率',
                rateType: '2',
                rateLevelName: '一至五年（含五年）',
              },
              {
                rateLevel: '29',
                rateTypeName: '央行基准利率',
                rateType: '2',
                rateLevelName: '五年以上',
              },
            ];
            await update({ path: me, action: 'load', value });
          }
          const openEdit = { editConfig: { enabled: !isReadonly } };
          await update({ path: me, action: 'attr', value: openEdit });
        },
      },
    },
  },
  /** 定价基准利率设置 结束 */
  {
    id: 'eFormDefMoneyUnit',
    component: 'Form',
    fields: [
      {
        field: '_.unit',
        title: '',
        component: 'Input',
        visible: false,
        defaultValue: 10000,
      },
    ],
    ui: {
      self: { class: 'hidden' },
      custom: { isSearch: true },
    },
  },
];
